'use client'

import { useState } from 'react'
import { Card, CardContent } from "@/components/ui/card"
import {
  Area,
  Bar,
  BarChart,
  ComposedChart,
  ResponsiveContainer,
  XAxis,
  YAxis,
  ReferenceLine,
  Customized,
  Cell,
} from 'recharts'

// 샘플 데이터 - 앞서는 경우
const SAMPLE_DATA_AHEAD = {
  cow: { name: '7805', score: 0.85 },      // 개체 (전국 기준)
  farm: { name: '농가', score: 0.53 },     // 농가 평균 (전국 기준)
  region: { name: '보은군', score: 0.21 }, // 보은군 평균 (전국 기준)
}

// 샘플 데이터 - 뒤처지는 경우
const SAMPLE_DATA_BEHIND = {
  cow: { name: '7805', score: 0.20 },      // 개체 (전국 기준)
  farm: { name: '농가', score: 0.53 },     // 농가 평균 (전국 기준)
  region: { name: '보은군', score: 0.60 }, // 보은군 평균 (전국 기준)
}

// 정규분포 히스토그램 데이터
const generateHistogramData = (min: number, max: number) => {
  const sigmaPercentMap: Record<string, number> = {
    '-3.0': 0.10, '-2.5': 2.3, '-2.0': 4.4, '-1.5': 9.2, '-1.0': 15.0,
    '-0.5': 19.1, '0.0': 19.1, '0.5': 15.0, '1.0': 9.2, '1.5': 4.4,
    '2.0': 2.3, '2.5': 0.10,
  }

  const data = []
  for (let sigma = min; sigma < max; sigma += 0.5) {
    const key = sigma.toFixed(1)
    const percent = sigmaPercentMap[key] ?? 0.1
    data.push({ midPoint: sigma + 0.25, percent })
  }
  return data
}

// 단일 미니 차트 컴포넌트
function MiniDistributionChart({
  title,
  baseLabel,
  baseColor,
  bgColor,
  borderColor,
  cowPosition,
  histogramData,
}: {
  title: string
  baseLabel: string
  baseColor: string
  bgColor: string
  borderColor: string
  cowPosition: number
  histogramData: { midPoint: number; percent: number }[]
}) {
  const isPositive = cowPosition >= 0

  return (
    <div className={`rounded-xl border-2 ${borderColor} ${bgColor} p-4`}>
      <div className="flex items-center justify-between mb-3">
        <div className="flex items-center gap-2">
          <div className={`w-3 h-3 rounded-full`} style={{ backgroundColor: baseColor }}></div>
          <span className="font-bold text-foreground">{title}</span>
        </div>
        <div className={`px-3 py-1 rounded-full text-white font-bold text-lg ${isPositive ? 'bg-green-500' : 'bg-red-500'}`}>
          {isPositive ? '+' : ''}{cowPosition.toFixed(2)}
        </div>
      </div>

      <div className="h-[180px]">
        <ResponsiveContainer width="100%" height="100%">
          <ComposedChart data={histogramData} margin={{ top: 30, right: 15, left: 5, bottom: 25 }}>
            <defs>
              <linearGradient id={`gradient-${baseLabel}`} x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor={baseColor} stopOpacity={0.4} />
                <stop offset="100%" stopColor={baseColor} stopOpacity={0.1} />
              </linearGradient>
            </defs>
            <XAxis
              dataKey="midPoint"
              type="number"
              domain={[-2, 2]}
              ticks={[-2, -1, 0, 1, 2]}
              tick={{ fontSize: 11, fill: '#64748b' }}
              tickLine={false}
              axisLine={{ stroke: '#e2e8f0' }}
              tickFormatter={(value) => value === 0 ? baseLabel : `${value > 0 ? '+' : ''}${value}`}
            />
            <YAxis hide />
            <Area type="natural" dataKey="percent" stroke={baseColor} strokeWidth={2} fill={`url(#gradient-${baseLabel})`} />
            <ReferenceLine x={0} stroke={baseColor} strokeWidth={2} strokeDasharray="4 2" />
            <ReferenceLine x={cowPosition} stroke="#1482B0" strokeWidth={3} />
            <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 [domainMin, domainMax] = xAxis.domain || [-2, 2]
                const domainRange = domainMax - domainMin
                const sigmaToX = (sigma: number) => chartX + ((sigma - domainMin) / domainRange) * chartWidth
                const cowX = sigmaToX(cowPosition)
                const baseX = sigmaToX(0)
                const badgeWidth = 70
                const minX = chartX + badgeWidth / 2 + 5
                const maxX = chartX + chartWidth - badgeWidth / 2 - 5
                const clampedCowX = Math.max(minX, Math.min(cowX, maxX))

                return (
                  <g>
                    <rect x={clampedCowX - 35} y={chartTop - 25} width={70} height={22} rx={4} fill="#1482B0" />
                    <text x={clampedCowX} y={chartTop - 10} textAnchor="middle" fill="white" fontSize={11} fontWeight={700}>내 개체</text>
                    <line x1={clampedCowX} y1={chartTop - 3} x2={cowX} y2={chartTop + 10} stroke="#1482B0" strokeWidth={1.5} strokeDasharray="3 2" />
                    {Math.abs(cowPosition) > 0.1 && (
                      <g>
                        <defs>
                          <marker id={`arrow-${baseLabel}`} markerWidth="8" markerHeight="8" refX="7" refY="3" orient="auto" markerUnits="strokeWidth">
                            <path d="M0,0 L0,6 L8,3 z" fill={baseColor} />
                          </marker>
                        </defs>
                        <line x1={cowX} y1={chartTop + 50} x2={baseX + (cowPosition > 0 ? 8 : -8)} y2={chartTop + 50} stroke={baseColor} strokeWidth={2} markerEnd={`url(#arrow-${baseLabel})`} />
                      </g>
                    )}
                  </g>
                )
              }}
            />
          </ComposedChart>
        </ResponsiveContainer>
      </div>
      <div className="text-center text-sm text-muted-foreground mt-2">
        {baseLabel} 평균보다 <span className={`font-bold ${isPositive ? 'text-green-600' : 'text-red-500'}`}>{isPositive ? '높음' : '낮음'}</span>
      </div>
    </div>
  )
}

export default function DualAxisDemo() {
  const [chartType, setChartType] = useState<'myCowCenter' | 'overlay' | 'cowCenter' | 'barCompare' | 'unified' | 'stack' | 'dual' | 'single'>('myCowCenter')
  const [viewMode, setViewMode] = useState<'dual' | 'farm' | 'region'>('dual')
  const [dataMode, setDataMode] = useState<'ahead' | 'behind'>('ahead')

  const SAMPLE_DATA = dataMode === 'ahead' ? SAMPLE_DATA_AHEAD : SAMPLE_DATA_BEHIND
  const cowScore = SAMPLE_DATA.cow.score
  const farmScore = SAMPLE_DATA.farm.score
  const regionScore = SAMPLE_DATA.region.score

  const cowVsFarm = cowScore - farmScore
  const cowVsRegion = cowScore - regionScore

  const histogramData = generateHistogramData(-2.5, 2.5)

  // 막대 비교 데이터
  const barData = [
    { name: '농가 대비', value: cowVsFarm, color: '#f59e0b' },
    { name: '보은군 대비', value: cowVsRegion, color: '#2563eb' },
  ]

  return (
    <div className="min-h-screen bg-slate-100 p-4 sm:p-8">
      <div className="max-w-4xl mx-auto space-y-6">
        <h1 className="text-2xl font-bold text-foreground">차트 비교 방식 데모</h1>

        {/* 데이터 모드 토글 */}
        <div className="flex items-center gap-3 p-3 bg-white rounded-lg border">
          <span className="text-sm font-medium text-muted-foreground">테스트 데이터:</span>
          <button
            onClick={() => setDataMode('ahead')}
            className={`px-4 py-2 rounded-lg font-medium transition-colors ${
              dataMode === 'ahead'
                ? 'bg-green-500 text-white'
                : 'bg-slate-100 text-slate-600 hover:bg-slate-200'
            }`}
          >
            평균보다 앞서는 경우
          </button>
          <button
            onClick={() => setDataMode('behind')}
            className={`px-4 py-2 rounded-lg font-medium transition-colors ${
              dataMode === 'behind'
                ? 'bg-red-500 text-white'
                : 'bg-slate-100 text-slate-600 hover:bg-slate-200'
            }`}
          >
            평균보다 뒤처지는 경우
          </button>
        </div>

        <p className="text-muted-foreground">
          개체: +{cowScore.toFixed(2)} | 농가: +{farmScore.toFixed(2)} | 보은군: +{regionScore.toFixed(2)} (전국 기준)
        </p>

        {/* 차트 타입 선택 */}
        <div className="flex flex-wrap gap-2">
          {[
            { id: 'myCowCenter', label: '내 개체 중심', desc: '추천' },
            { id: 'overlay', label: '오버레이' },
            { id: 'cowCenter', label: '개체 중심(구)' },
            { id: 'barCompare', label: '막대 비교' },
            { id: 'unified', label: '통합 차트' },
            { id: 'stack', label: '스택 차트' },
            { id: 'dual', label: '듀얼 X축' },
            { id: 'single', label: '토글 방식' },
          ].map((type) => (
            <button
              key={type.id}
              onClick={() => setChartType(type.id as any)}
              className={`px-4 py-2 rounded-lg font-medium transition-colors ${
                chartType === type.id
                  ? 'bg-primary text-white'
                  : 'bg-white text-foreground hover:bg-slate-200'
              }`}
            >
              {type.label}
              {type.desc && <span className="ml-1 text-xs opacity-75">({type.desc})</span>}
            </button>
          ))}
        </div>

        {/* ============ 내 개체 중심 차트 (추천) ============ */}
        {chartType === 'myCowCenter' && (() => {
          // 개체가 앞서는지 뒤처지는지 판단
          const isAhead = cowVsFarm >= 0 && cowVsRegion >= 0
          const isBehind = cowVsFarm < 0 && cowVsRegion < 0
          const isMixed = !isAhead && !isBehind

          // X축 도메인 계산 (동적으로)
          const maxDiff = Math.max(Math.abs(cowVsFarm), Math.abs(cowVsRegion))
          const domainPadding = 0.3
          const xDomain: [number, number] = isAhead || isMixed
            ? [-(maxDiff + domainPadding), domainPadding]
            : [-domainPadding, maxDiff + domainPadding]

          // 색상 설정
          const mainColor = isAhead ? '#22c55e' : isBehind ? '#ef4444' : '#f59e0b'
          const bgColorClass = isAhead ? 'from-green-50 to-green-100' : isBehind ? 'from-red-50 to-red-100' : 'from-amber-50 to-amber-100'

          return (
            <Card>
              <CardContent className="p-4">
                <h2 className="text-lg font-bold mb-2">내 개체 중심 비교</h2>
                <p className="text-sm text-muted-foreground mb-4">
                  {isAhead && '내 개체 기준으로, 농가/보은군 평균이 얼마나 뒤처져 있는지 표시'}
                  {isBehind && '내 개체 기준으로, 농가/보은군 평균이 얼마나 앞서 있는지 표시'}
                  {isMixed && '내 개체 기준으로, 농가/보은군 평균과의 차이 표시'}
                </p>

                {/* 큰 결과 표시 */}
                <div className="grid grid-cols-2 gap-3 mb-4">
                  <div className={`p-4 rounded-xl bg-gradient-to-br ${cowVsFarm >= 0 ? 'from-amber-50 to-amber-100 border-amber-400' : 'from-amber-50 to-red-100 border-red-400'} border-2`}>
                    <div className="text-sm text-amber-700 font-medium mb-1">농가 평균보다</div>
                    <div className={`text-3xl font-black ${cowVsFarm >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                      {cowVsFarm >= 0 ? '+' : ''}{cowVsFarm.toFixed(2)}
                    </div>
                    <div className={`text-sm ${cowVsFarm >= 0 ? 'text-green-600' : 'text-red-600'} mt-1 font-medium`}>
                      {cowVsFarm >= 0 ? '상위권' : '하위권'}
                    </div>
                  </div>
                  <div className={`p-4 rounded-xl bg-gradient-to-br ${cowVsRegion >= 0 ? 'from-blue-50 to-blue-100 border-blue-400' : 'from-blue-50 to-red-100 border-red-400'} border-2`}>
                    <div className="text-sm text-blue-700 font-medium mb-1">보은군 평균보다</div>
                    <div className={`text-3xl font-black ${cowVsRegion >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                      {cowVsRegion >= 0 ? '+' : ''}{cowVsRegion.toFixed(2)}
                    </div>
                    <div className={`text-sm ${cowVsRegion >= 0 ? 'text-green-600' : 'text-red-600'} mt-1 font-medium`}>
                      {cowVsRegion >= 0 ? '상위권' : '하위권'}
                    </div>
                  </div>
                </div>

                <div className={`h-[320px] bg-gradient-to-b ${bgColorClass} rounded-xl p-4`}>
                  <ResponsiveContainer width="100%" height="100%">
                    <ComposedChart data={histogramData} margin={{ top: 50, right: 80, left: 40, bottom: 40 }}>
                      <defs>
                        <linearGradient id="myCowGradient" x1="0" y1="0" x2="0" y2="1">
                          <stop offset="0%" stopColor={mainColor} stopOpacity={0.5} />
                          <stop offset="100%" stopColor={mainColor} stopOpacity={0.1} />
                        </linearGradient>
                      </defs>

                      <XAxis
                        dataKey="midPoint"
                        type="number"
                        domain={xDomain}
                        tick={{ fontSize: 12, fill: '#64748b', fontWeight: 600 }}
                        tickLine={false}
                        axisLine={{ stroke: '#cbd5e1', strokeWidth: 2 }}
                        tickFormatter={() => ''}
                      />
                      <YAxis hide />

                      {/* 정규분포 곡선 */}
                      <Area
                        type="natural"
                        dataKey="percent"
                        stroke={mainColor}
                        strokeWidth={3}
                        fill="url(#myCowGradient)"
                      />

                      {/* 내 개체 (기준선 = 0) */}
                      <ReferenceLine x={0} stroke="#1482B0" strokeWidth={4} />

                      {/* 농가 평균 위치 */}
                      <ReferenceLine x={-cowVsFarm} stroke="#f59e0b" strokeWidth={3} strokeDasharray="6 3" />

                      {/* 보은군 평균 위치 */}
                      <ReferenceLine x={-cowVsRegion} stroke="#2563eb" strokeWidth={3} strokeDasharray="6 3" />

                      <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 chartHeight = yAxis.height
                          const chartBottom = chartTop + chartHeight
                          const [dMin, dMax] = xAxis.domain || xDomain
                          const domainRange = dMax - dMin
                          const sigmaToX = (sigma: number) => chartX + ((sigma - dMin) / domainRange) * chartWidth

                          const cowX = sigmaToX(0)
                          const farmX = sigmaToX(-cowVsFarm)
                          const regionX = sigmaToX(-cowVsRegion)

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

                          return (
                            <g>
                              {/* 내 개체 배지 */}
                              <rect
                                x={clamp(cowX, 37) - 37}
                                y={chartTop - 40}
                                width={75}
                                height={36}
                                rx={8}
                                fill="#1482B0"
                                filter="drop-shadow(0 2px 4px rgba(0,0,0,0.2))"
                              />
                              <text x={clamp(cowX, 37)} y={chartTop - 18} textAnchor="middle" fill="white" fontSize={14} fontWeight={800}>
                                내 개체
                              </text>
                              <line x1={clamp(cowX, 37)} y1={chartTop - 4} x2={cowX} y2={chartTop + 5} stroke="#1482B0" strokeWidth={2} />

                              {/* 농가 평균 배지 */}
                              <rect
                                x={clamp(farmX, 45) - 45}
                                y={chartTop + 15}
                                width={90}
                                height={32}
                                rx={6}
                                fill="#f59e0b"
                                filter="drop-shadow(0 2px 4px rgba(0,0,0,0.15))"
                              />
                              <text x={clamp(farmX, 45)} y={chartTop + 37} textAnchor="middle" fill="white" fontSize={13} fontWeight={700}>
                                농가 평균
                              </text>
                              <line x1={clamp(farmX, 45)} y1={chartTop + 47} x2={farmX} y2={chartTop + 60} stroke="#f59e0b" strokeWidth={2} />

                              {/* 보은군 평균 배지 */}
                              <rect
                                x={clamp(regionX, 50) - 50}
                                y={chartTop + 55}
                                width={100}
                                height={32}
                                rx={6}
                                fill="#2563eb"
                                filter="drop-shadow(0 2px 4px rgba(0,0,0,0.15))"
                              />
                              <text x={clamp(regionX, 50)} y={chartTop + 77} textAnchor="middle" fill="white" fontSize={13} fontWeight={700}>
                                보은군 평균
                              </text>
                              <line x1={clamp(regionX, 50)} y1={chartTop + 87} x2={regionX} y2={chartTop + 100} stroke="#2563eb" strokeWidth={2} />

                              {/* 화살표 마커 정의 */}
                              <defs>
                                <marker id="arrowGreen" markerWidth="10" markerHeight="10" refX="9" refY="3" orient="auto">
                                  <path d="M0,0 L0,6 L9,3 z" fill="#22c55e" />
                                </marker>
                                <marker id="arrowRed" markerWidth="10" markerHeight="10" refX="9" refY="3" orient="auto">
                                  <path d="M0,0 L0,6 L9,3 z" fill="#ef4444" />
                                </marker>
                                <marker id="arrowRedLeft" markerWidth="10" markerHeight="10" refX="1" refY="3" orient="auto-start-reverse">
                                  <path d="M0,0 L0,6 L9,3 z" fill="#ef4444" />
                                </marker>
                              </defs>

                              {/* 농가 vs 개체 거리 화살표 */}
                              {Math.abs(cowVsFarm) > 0.05 && (
                                <g>
                                  <line
                                    x1={cowVsFarm >= 0 ? farmX + 5 : cowX + 5}
                                    y1={chartTop + chartHeight * 0.65}
                                    x2={cowVsFarm >= 0 ? cowX - 5 : farmX - 5}
                                    y2={chartTop + chartHeight * 0.65}
                                    stroke={cowVsFarm >= 0 ? '#22c55e' : '#ef4444'}
                                    strokeWidth={3}
                                    markerEnd={cowVsFarm >= 0 ? 'url(#arrowGreen)' : undefined}
                                    markerStart={cowVsFarm >= 0 ? undefined : 'url(#arrowRedLeft)'}
                                  />
                                  <rect
                                    x={(farmX + cowX) / 2 - 30}
                                    y={chartTop + chartHeight * 0.65 - 25}
                                    width={60}
                                    height={22}
                                    rx={4}
                                    fill={cowVsFarm >= 0 ? '#22c55e' : '#ef4444'}
                                  />
                                  <text
                                    x={(farmX + cowX) / 2}
                                    y={chartTop + chartHeight * 0.65 - 10}
                                    textAnchor="middle"
                                    fill="white"
                                    fontSize={12}
                                    fontWeight={800}
                                  >
                                    {cowVsFarm >= 0 ? '+' : ''}{cowVsFarm.toFixed(2)}
                                  </text>
                                </g>
                              )}

                              {/* 보은군 vs 개체 거리 화살표 */}
                              {Math.abs(cowVsRegion) > 0.05 && (
                                <g>
                                  <line
                                    x1={cowVsRegion >= 0 ? regionX + 5 : cowX + 5}
                                    y1={chartTop + chartHeight * 0.82}
                                    x2={cowVsRegion >= 0 ? cowX - 5 : regionX - 5}
                                    y2={chartTop + chartHeight * 0.82}
                                    stroke={cowVsRegion >= 0 ? '#22c55e' : '#ef4444'}
                                    strokeWidth={3}
                                    markerEnd={cowVsRegion >= 0 ? 'url(#arrowGreen)' : undefined}
                                    markerStart={cowVsRegion >= 0 ? undefined : 'url(#arrowRedLeft)'}
                                  />
                                  <rect
                                    x={(regionX + cowX) / 2 - 30}
                                    y={chartTop + chartHeight * 0.82 - 25}
                                    width={60}
                                    height={22}
                                    rx={4}
                                    fill={cowVsRegion >= 0 ? '#22c55e' : '#ef4444'}
                                  />
                                  <text
                                    x={(regionX + cowX) / 2}
                                    y={chartTop + chartHeight * 0.82 - 10}
                                    textAnchor="middle"
                                    fill="white"
                                    fontSize={12}
                                    fontWeight={800}
                                  >
                                    {cowVsRegion >= 0 ? '+' : ''}{cowVsRegion.toFixed(2)}
                                  </text>
                                </g>
                              )}

                              {/* X축 아래 설명 */}
                              <text x={farmX} y={chartBottom + 25} textAnchor="middle" fill="#f59e0b" fontSize={11} fontWeight={600}>
                                농가
                              </text>
                              <text x={regionX} y={chartBottom + 25} textAnchor="middle" fill="#2563eb" fontSize={11} fontWeight={600}>
                                보은군
                              </text>
                              <text x={cowX} y={chartBottom + 25} textAnchor="middle" fill="#1482B0" fontSize={12} fontWeight={700}>
                                내 개체
                              </text>

                              {/* 좋음/나쁨 표시 */}
                              <text x={chartX + chartWidth + 10} y={chartTop + chartHeight / 2 - 8} textAnchor="start" fill="#22c55e" fontSize={11} fontWeight={600}>
                                좋음 →
                              </text>
                              <text x={chartX - 10} y={chartTop + chartHeight / 2 - 8} textAnchor="end" fill="#ef4444" fontSize={11} fontWeight={600}>
                                ← 나쁨
                              </text>
                            </g>
                          )
                        }}
                      />
                    </ComposedChart>
                  </ResponsiveContainer>
                </div>

                {/* 하단 설명 */}
                <div className={`mt-4 p-4 ${isAhead ? 'bg-green-50 border-green-200' : isBehind ? 'bg-red-50 border-red-200' : 'bg-amber-50 border-amber-200'} border-2 rounded-xl`}>
                  <div className="text-center">
                    <div className={`text-lg font-bold ${isAhead ? 'text-green-700' : isBehind ? 'text-red-700' : 'text-amber-700'} mb-1`}>
                      {isAhead && '내 개체가 평균보다 우수합니다!'}
                      {isBehind && '내 개체가 평균보다 낮습니다'}
                      {isMixed && '농가/보은군에 따라 다릅니다'}
                    </div>
                    <div className={`text-sm ${isAhead ? 'text-green-600' : isBehind ? 'text-red-600' : 'text-amber-600'}`}>
                      {isAhead && '오른쪽으로 갈수록 좋음 → 내 개체가 가장 오른쪽에 위치'}
                      {isBehind && '평균들이 내 개체보다 오른쪽에 위치 → 개선이 필요합니다'}
                      {isMixed && '일부 평균보다 높고 일부보다 낮습니다'}
                    </div>
                  </div>
                </div>

                {/* 범례 */}
                <div className="flex items-center justify-center gap-6 mt-4 pt-4 border-t">
                  <div className="flex items-center gap-2">
                    <div className="w-4 h-4 rounded bg-primary"></div>
                    <span className="text-sm font-bold">내 개체</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <div className="w-4 h-1 bg-amber-500"></div>
                    <span className="text-sm text-muted-foreground">농가 평균</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <div className="w-4 h-1 bg-blue-500"></div>
                    <span className="text-sm text-muted-foreground">보은군 평균</span>
                  </div>
                </div>
              </CardContent>
            </Card>
          )
        })()}

        {/* ============ 오버레이 차트 ============ */}
        {chartType === 'overlay' && (
          <Card>
            <CardContent className="p-4">
              <h2 className="text-lg font-bold mb-2">오버레이 차트</h2>
              <p className="text-sm text-muted-foreground mb-4">
                농가 기준(주황)과 보은군 기준(파랑) 정규분포를 한 차트에 겹쳐서 표시
              </p>

              {/* 요약 카드 */}
              <div className="grid grid-cols-2 gap-3 mb-4">
                <div className="p-3 rounded-xl border-2 border-amber-400 bg-amber-50">
                  <div className="flex items-center gap-2 mb-1">
                    <div className="w-3 h-3 rounded-full bg-amber-500"></div>
                    <span className="text-sm font-medium text-amber-700">농가 기준</span>
                  </div>
                  <div className={`text-2xl font-bold ${cowVsFarm >= 0 ? 'text-green-600' : 'text-red-500'}`}>
                    {cowVsFarm >= 0 ? '+' : ''}{cowVsFarm.toFixed(2)}
                  </div>
                  <div className="text-xs text-muted-foreground">농가 평균보다 {cowVsFarm >= 0 ? '높음' : '낮음'}</div>
                </div>
                <div className="p-3 rounded-xl border-2 border-blue-400 bg-blue-50">
                  <div className="flex items-center gap-2 mb-1">
                    <div className="w-3 h-3 rounded-full bg-blue-500"></div>
                    <span className="text-sm font-medium text-blue-700">보은군 기준</span>
                  </div>
                  <div className={`text-2xl font-bold ${cowVsRegion >= 0 ? 'text-green-600' : 'text-red-500'}`}>
                    {cowVsRegion >= 0 ? '+' : ''}{cowVsRegion.toFixed(2)}
                  </div>
                  <div className="text-xs text-muted-foreground">보은군 평균보다 {cowVsRegion >= 0 ? '높음' : '낮음'}</div>
                </div>
              </div>

              <div className="h-[380px] bg-slate-50 rounded-xl p-4">
                <ResponsiveContainer width="100%" height="100%">
                  <ComposedChart data={histogramData} margin={{ top: 60, right: 20, left: 10, bottom: 40 }}>
                    <defs>
                      {/* 농가 기준 그라디언트 */}
                      <linearGradient id="overlayFarmGradient" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="0%" stopColor="#f59e0b" stopOpacity={0.35} />
                        <stop offset="100%" stopColor="#f59e0b" stopOpacity={0.05} />
                      </linearGradient>
                      {/* 보은군 기준 그라디언트 */}
                      <linearGradient id="overlayRegionGradient" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="0%" stopColor="#2563eb" stopOpacity={0.35} />
                        <stop offset="100%" stopColor="#2563eb" stopOpacity={0.05} />
                      </linearGradient>
                    </defs>

                    <XAxis
                      dataKey="midPoint"
                      type="number"
                      domain={[-2, 2]}
                      ticks={[-2, -1, 0, 1, 2]}
                      tick={{ fontSize: 11, fill: '#64748b' }}
                      tickLine={false}
                      axisLine={{ stroke: '#e2e8f0' }}
                      tickFormatter={(v) => v === 0 ? '기준' : `${v > 0 ? '+' : ''}${v}`}
                    />
                    <YAxis hide />

                    {/* 농가 기준 정규분포 (주황) */}
                    <Area
                      type="natural"
                      dataKey="percent"
                      stroke="#f59e0b"
                      strokeWidth={2.5}
                      fill="url(#overlayFarmGradient)"
                      strokeDasharray="0"
                    />

                    {/* 보은군 기준 정규분포 (파랑) - 같은 데이터지만 시각적으로 구분 */}
                    <Area
                      type="natural"
                      dataKey="percent"
                      stroke="#2563eb"
                      strokeWidth={2.5}
                      fill="url(#overlayRegionGradient)"
                      strokeDasharray="5 3"
                    />

                    {/* 농가 기준 0선 (농가 평균) */}
                    <ReferenceLine x={0} stroke="#f59e0b" strokeWidth={2} strokeDasharray="4 2" />

                    {/* 보은군 기준 0선 (보은군 평균) - 같은 위치 */}
                    <ReferenceLine x={0} stroke="#2563eb" strokeWidth={2} strokeDasharray="4 2" />

                    {/* 농가 기준 개체 위치 */}
                    <ReferenceLine x={cowVsFarm} stroke="#f59e0b" strokeWidth={3} />

                    {/* 보은군 기준 개체 위치 */}
                    <ReferenceLine x={cowVsRegion} stroke="#2563eb" strokeWidth={3} />

                    <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 chartHeight = yAxis.height
                        const chartBottom = chartTop + chartHeight
                        const [domainMin, domainMax] = xAxis.domain || [-2, 2]
                        const domainRange = domainMax - domainMin
                        const sigmaToX = (sigma: number) => chartX + ((sigma - domainMin) / domainRange) * chartWidth

                        const baseX = sigmaToX(0)
                        const farmCowX = sigmaToX(cowVsFarm)
                        const regionCowX = sigmaToX(cowVsRegion)

                        // 배지 위치 클램핑
                        const clamp = (x: number, width: number) => {
                          const minX = chartX + width / 2 + 5
                          const maxX = chartX + chartWidth - width / 2 - 5
                          return Math.max(minX, Math.min(x, maxX))
                        }

                        return (
                          <g>
                            {/* 기준점 라벨 (중앙) */}
                            <text x={baseX} y={chartBottom + 30} textAnchor="middle" fill="#64748b" fontSize={11} fontWeight={600}>
                              농가/보은군 평균
                            </text>

                            {/* 농가 기준 개체 배지 (상단) */}
                            <rect x={clamp(farmCowX, 100) - 50} y={chartTop - 50} width={100} height={28} rx={5} fill="#f59e0b" />
                            <text x={clamp(farmCowX, 100)} y={chartTop - 32} textAnchor="middle" fill="white" fontSize={12} fontWeight={700}>
                              농가 대비 +{cowVsFarm.toFixed(2)}
                            </text>
                            {/* 연결선 */}
                            <line
                              x1={clamp(farmCowX, 100)}
                              y1={chartTop - 22}
                              x2={farmCowX}
                              y2={chartTop + 5}
                              stroke="#f59e0b"
                              strokeWidth={1.5}
                              strokeDasharray="3 2"
                            />

                            {/* 보은군 기준 개체 배지 (상단, 약간 아래) */}
                            <rect x={clamp(regionCowX, 110) - 55} y={chartTop - 20} width={110} height={28} rx={5} fill="#2563eb" />
                            <text x={clamp(regionCowX, 110)} y={chartTop - 2} textAnchor="middle" fill="white" fontSize={12} fontWeight={700}>
                              보은군 대비 +{cowVsRegion.toFixed(2)}
                            </text>
                            {/* 연결선 */}
                            <line
                              x1={clamp(regionCowX, 110)}
                              y1={chartTop + 8}
                              x2={regionCowX}
                              y2={chartTop + 25}
                              stroke="#2563eb"
                              strokeWidth={1.5}
                              strokeDasharray="3 2"
                            />

                            {/* 개체 마커 - 농가 기준 */}
                            <circle cx={farmCowX} cy={chartTop + chartHeight * 0.35} r={8} fill="#f59e0b" stroke="white" strokeWidth={2} />
                            <text x={farmCowX} y={chartTop + chartHeight * 0.35 + 4} textAnchor="middle" fill="white" fontSize={9} fontWeight={700}>
                              F
                            </text>

                            {/* 개체 마커 - 보은군 기준 */}
                            <circle cx={regionCowX} cy={chartTop + chartHeight * 0.55} r={8} fill="#2563eb" stroke="white" strokeWidth={2} />
                            <text x={regionCowX} y={chartTop + chartHeight * 0.55 + 4} textAnchor="middle" fill="white" fontSize={9} fontWeight={700}>
                              R
                            </text>

                            {/* 화살표: 기준 → 농가 개체 위치 */}
                            <defs>
                              <marker id="arrowFarmOverlay" markerWidth="8" markerHeight="8" refX="7" refY="3" orient="auto">
                                <path d="M0,0 L0,6 L8,3 z" fill="#f59e0b" />
                              </marker>
                              <marker id="arrowRegionOverlay" markerWidth="8" markerHeight="8" refX="7" refY="3" orient="auto">
                                <path d="M0,0 L0,6 L8,3 z" fill="#2563eb" />
                              </marker>
                            </defs>

                            {cowVsFarm > 0.1 && (
                              <line
                                x1={baseX + 5}
                                y1={chartTop + chartHeight * 0.35}
                                x2={farmCowX - 12}
                                y2={chartTop + chartHeight * 0.35}
                                stroke="#f59e0b"
                                strokeWidth={2}
                                markerEnd="url(#arrowFarmOverlay)"
                              />
                            )}

                            {cowVsRegion > 0.1 && (
                              <line
                                x1={baseX + 5}
                                y1={chartTop + chartHeight * 0.55}
                                x2={regionCowX - 12}
                                y2={chartTop + chartHeight * 0.55}
                                stroke="#2563eb"
                                strokeWidth={2}
                                markerEnd="url(#arrowRegionOverlay)"
                              />
                            )}
                          </g>
                        )
                      }}
                    />
                  </ComposedChart>
                </ResponsiveContainer>
              </div>

              {/* 범례 */}
              <div className="flex items-center justify-center gap-6 mt-4 pt-4 border-t">
                <div className="flex items-center gap-2">
                  <div className="w-8 h-0.5 bg-amber-500"></div>
                  <div className="w-4 h-4 rounded-full bg-amber-500 text-white text-[8px] flex items-center justify-center font-bold">F</div>
                  <span className="text-sm text-muted-foreground">농가 기준 개체</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-8 h-0.5 bg-blue-500" style={{ backgroundImage: 'repeating-linear-gradient(90deg, #2563eb 0, #2563eb 5px, transparent 5px, transparent 8px)' }}></div>
                  <div className="w-4 h-4 rounded-full bg-blue-500 text-white text-[8px] flex items-center justify-center font-bold">R</div>
                  <span className="text-sm text-muted-foreground">보은군 기준 개체</span>
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        {/* ============ 개체 중심 비교 ============ */}
        {chartType === 'cowCenter' && (
          <Card>
            <CardContent className="p-4">
              <h2 className="text-lg font-bold mb-2">개체 중심 비교</h2>
              <p className="text-sm text-muted-foreground mb-4">
                내 개체를 기준(0)으로, 농가/보은군이 얼마나 뒤처져 있는지 한눈에 확인
              </p>

              <div className="h-[350px] bg-slate-50 rounded-xl p-4">
                <ResponsiveContainer width="100%" height="100%">
                  <ComposedChart data={histogramData} margin={{ top: 80, right: 30, left: 30, bottom: 50 }}>
                    <defs>
                      <linearGradient id="cowCenterGradient" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="0%" stopColor="#1482B0" stopOpacity={0.4} />
                        <stop offset="100%" stopColor="#1482B0" stopOpacity={0.1} />
                      </linearGradient>
                    </defs>
                    <XAxis
                      dataKey="midPoint"
                      type="number"
                      domain={[-1.5, 1.5]}
                      ticks={[-1, -0.5, 0, 0.5, 1]}
                      tick={{ fontSize: 12, fill: '#64748b' }}
                      tickLine={false}
                      axisLine={{ stroke: '#e2e8f0' }}
                      tickFormatter={(value) => {
                        if (value === 0) return '내 개체'
                        return `${value > 0 ? '+' : ''}${value.toFixed(1)}`
                      }}
                    />
                    <YAxis hide />
                    <Area type="natural" dataKey="percent" stroke="#1482B0" strokeWidth={2} fill="url(#cowCenterGradient)" />

                    {/* 내 개체 (중심선) */}
                    <ReferenceLine x={0} stroke="#1482B0" strokeWidth={3} />

                    {/* 농가 위치 (개체 기준) */}
                    <ReferenceLine x={-cowVsFarm} stroke="#f59e0b" strokeWidth={2.5} strokeDasharray="5 3" />

                    {/* 보은군 위치 (개체 기준) */}
                    <ReferenceLine x={-cowVsRegion} stroke="#2563eb" strokeWidth={2.5} strokeDasharray="5 3" />

                    <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 chartHeight = yAxis.height
                        const chartBottom = chartTop + chartHeight
                        const [domainMin, domainMax] = xAxis.domain || [-1.5, 1.5]
                        const domainRange = domainMax - domainMin
                        const sigmaToX = (sigma: number) => chartX + ((sigma - domainMin) / domainRange) * chartWidth

                        const cowX = sigmaToX(0)
                        const farmX = sigmaToX(-cowVsFarm)
                        const regionX = sigmaToX(-cowVsRegion)

                        return (
                          <g>
                            {/* 내 개체 배지 (중앙 상단) */}
                            <rect x={cowX - 50} y={chartTop - 65} width={100} height={30} rx={6} fill="#1482B0" />
                            <text x={cowX} y={chartTop - 45} textAnchor="middle" fill="white" fontSize={14} fontWeight={700}>
                              내 개체 (기준)
                            </text>
                            <line x1={cowX} y1={chartTop - 35} x2={cowX} y2={chartTop} stroke="#1482B0" strokeWidth={2} />

                            {/* 농가 배지 */}
                            <rect x={farmX - 60} y={chartTop - 35} width={120} height={28} rx={5} fill="#f59e0b" />
                            <text x={farmX} y={chartTop - 17} textAnchor="middle" fill="white" fontSize={12} fontWeight={700}>
                              농가 ({cowVsFarm >= 0 ? '-' : '+'}{Math.abs(cowVsFarm).toFixed(2)} 뒤)
                            </text>

                            {/* 보은군 배지 */}
                            <rect x={regionX - 65} y={chartBottom + 15} width={130} height={28} rx={5} fill="#2563eb" />
                            <text x={regionX} y={chartBottom + 33} textAnchor="middle" fill="white" fontSize={12} fontWeight={700}>
                              보은군 ({cowVsRegion >= 0 ? '-' : '+'}{Math.abs(cowVsRegion).toFixed(2)} 뒤)
                            </text>

                            {/* 화살표: 농가 → 개체 */}
                            <defs>
                              <marker id="arrowToRight" markerWidth="10" markerHeight="10" refX="9" refY="3" orient="auto">
                                <path d="M0,0 L0,6 L9,3 z" fill="#22c55e" />
                              </marker>
                            </defs>
                            <line
                              x1={farmX}
                              y1={chartTop + chartHeight * 0.35}
                              x2={cowX - 8}
                              y2={chartTop + chartHeight * 0.35}
                              stroke="#22c55e"
                              strokeWidth={3}
                              markerEnd="url(#arrowToRight)"
                            />
                            <rect x={(farmX + cowX) / 2 - 30} y={chartTop + chartHeight * 0.35 - 25} width={60} height={20} rx={4} fill="#22c55e" />
                            <text x={(farmX + cowX) / 2} y={chartTop + chartHeight * 0.35 - 11} textAnchor="middle" fill="white" fontSize={11} fontWeight={700}>
                              +{cowVsFarm.toFixed(2)}
                            </text>

                            {/* 화살표: 보은군 → 개체 */}
                            <line
                              x1={regionX}
                              y1={chartTop + chartHeight * 0.55}
                              x2={cowX - 8}
                              y2={chartTop + chartHeight * 0.55}
                              stroke="#22c55e"
                              strokeWidth={3}
                              markerEnd="url(#arrowToRight)"
                            />
                            <rect x={(regionX + cowX) / 2 - 30} y={chartTop + chartHeight * 0.55 - 25} width={60} height={20} rx={4} fill="#22c55e" />
                            <text x={(regionX + cowX) / 2} y={chartTop + chartHeight * 0.55 - 11} textAnchor="middle" fill="white" fontSize={11} fontWeight={700}>
                              +{cowVsRegion.toFixed(2)}
                            </text>
                          </g>
                        )
                      }}
                    />
                  </ComposedChart>
                </ResponsiveContainer>
              </div>

              {/* 요약 */}
              <div className="mt-4 p-4 bg-green-50 border border-green-200 rounded-xl">
                <div className="text-center space-y-1">
                  <div className="text-lg font-bold text-green-700">내 개체가 더 우수합니다!</div>
                  <div className="text-sm text-muted-foreground">
                    농가 평균보다 <span className="font-bold text-amber-600">+{cowVsFarm.toFixed(2)}</span>,
                    보은군 평균보다 <span className="font-bold text-blue-600">+{cowVsRegion.toFixed(2)}</span> 높음
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        {/* ============ 막대 비교 차트 ============ */}
        {chartType === 'barCompare' && (
          <Card>
            <CardContent className="p-4">
              <h2 className="text-lg font-bold mb-2">막대 비교 차트</h2>
              <p className="text-sm text-muted-foreground mb-4">
                정규분포 대신 단순 막대로 비교 - 가장 직관적
              </p>

              <div className="space-y-6">
                {/* 농가 대비 */}
                <div className="p-4 bg-amber-50 border-2 border-amber-300 rounded-xl">
                  <div className="flex items-center justify-between mb-3">
                    <span className="font-bold text-amber-700">농가 평균 대비</span>
                    <span className={`text-2xl font-bold ${cowVsFarm >= 0 ? 'text-green-600' : 'text-red-500'}`}>
                      {cowVsFarm >= 0 ? '+' : ''}{cowVsFarm.toFixed(2)}
                    </span>
                  </div>
                  <div className="relative h-10 bg-slate-200 rounded-full overflow-hidden">
                    <div className="absolute inset-y-0 left-1/2 w-0.5 bg-slate-400 z-10"></div>
                    <div
                      className={`absolute inset-y-0 ${cowVsFarm >= 0 ? 'left-1/2' : 'right-1/2'} bg-gradient-to-r from-amber-400 to-amber-500 rounded-full transition-all duration-500`}
                      style={{ width: `${Math.min(Math.abs(cowVsFarm) * 30, 50)}%` }}
                    ></div>
                    <div className="absolute inset-y-0 left-1/2 transform -translate-x-1/2 flex items-center">
                      <div className="w-4 h-4 rounded-full bg-amber-600 border-2 border-white shadow"></div>
                    </div>
                    <div
                      className="absolute inset-y-0 flex items-center"
                      style={{ left: `${50 + cowVsFarm * 30}%`, transform: 'translateX(-50%)' }}
                    >
                      <div className="w-6 h-6 rounded-full bg-primary border-2 border-white shadow-lg"></div>
                    </div>
                  </div>
                  <div className="flex justify-between mt-2 text-xs text-muted-foreground">
                    <span>낮음</span>
                    <span className="font-medium text-amber-600">농가 평균</span>
                    <span>높음</span>
                  </div>
                </div>

                {/* 보은군 대비 */}
                <div className="p-4 bg-blue-50 border-2 border-blue-300 rounded-xl">
                  <div className="flex items-center justify-between mb-3">
                    <span className="font-bold text-blue-700">보은군 평균 대비</span>
                    <span className={`text-2xl font-bold ${cowVsRegion >= 0 ? 'text-green-600' : 'text-red-500'}`}>
                      {cowVsRegion >= 0 ? '+' : ''}{cowVsRegion.toFixed(2)}
                    </span>
                  </div>
                  <div className="relative h-10 bg-slate-200 rounded-full overflow-hidden">
                    <div className="absolute inset-y-0 left-1/2 w-0.5 bg-slate-400 z-10"></div>
                    <div
                      className={`absolute inset-y-0 ${cowVsRegion >= 0 ? 'left-1/2' : 'right-1/2'} bg-gradient-to-r from-blue-400 to-blue-500 rounded-full transition-all duration-500`}
                      style={{ width: `${Math.min(Math.abs(cowVsRegion) * 30, 50)}%` }}
                    ></div>
                    <div className="absolute inset-y-0 left-1/2 transform -translate-x-1/2 flex items-center">
                      <div className="w-4 h-4 rounded-full bg-blue-600 border-2 border-white shadow"></div>
                    </div>
                    <div
                      className="absolute inset-y-0 flex items-center"
                      style={{ left: `${50 + cowVsRegion * 30}%`, transform: 'translateX(-50%)' }}
                    >
                      <div className="w-6 h-6 rounded-full bg-primary border-2 border-white shadow-lg"></div>
                    </div>
                  </div>
                  <div className="flex justify-between mt-2 text-xs text-muted-foreground">
                    <span>낮음</span>
                    <span className="font-medium text-blue-600">보은군 평균</span>
                    <span>높음</span>
                  </div>
                </div>

                {/* 범례 */}
                <div className="flex items-center justify-center gap-6 pt-2">
                  <div className="flex items-center gap-2">
                    <div className="w-4 h-4 rounded-full bg-primary"></div>
                    <span className="text-sm font-medium">내 개체</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <div className="w-3 h-3 rounded-full bg-amber-500"></div>
                    <span className="text-sm text-muted-foreground">농가 평균</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <div className="w-3 h-3 rounded-full bg-blue-500"></div>
                    <span className="text-sm text-muted-foreground">보은군 평균</span>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        {/* ============ 통합 차트 (하나의 정규분포 + 3개 마커) ============ */}
        {chartType === 'unified' && (
          <Card>
            <CardContent className="p-4">
              <h2 className="text-lg font-bold mb-2">통합 차트</h2>
              <p className="text-sm text-muted-foreground mb-4">
                하나의 정규분포에 농가/보은군/개체 모두 표시 + 대비값 강조
              </p>

              <div className="h-[400px] bg-slate-50 rounded-xl p-4">
                <ResponsiveContainer width="100%" height="100%">
                  <ComposedChart data={histogramData} margin={{ top: 100, right: 30, left: 10, bottom: 60 }}>
                    <defs>
                      <linearGradient id="unifiedGradient" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="0%" stopColor="#3b82f6" stopOpacity={0.4} />
                        <stop offset="100%" stopColor="#93c5fd" stopOpacity={0.1} />
                      </linearGradient>
                    </defs>
                    <XAxis
                      dataKey="midPoint"
                      type="number"
                      domain={[-2, 2]}
                      ticks={[-2, -1, 0, 1, 2]}
                      tick={{ fontSize: 11, fill: '#64748b' }}
                      tickLine={false}
                      axisLine={{ stroke: '#e2e8f0' }}
                      tickFormatter={(v) => v === 0 ? '전국평균' : `${v > 0 ? '+' : ''}${v}`}
                    />
                    <YAxis hide />
                    <Area type="natural" dataKey="percent" stroke="#3b82f6" strokeWidth={2} fill="url(#unifiedGradient)" />

                    <ReferenceLine x={regionScore} stroke="#2563eb" strokeWidth={2.5} strokeDasharray="5 3" />
                    <ReferenceLine x={farmScore} stroke="#f59e0b" strokeWidth={2.5} strokeDasharray="5 3" />
                    <ReferenceLine x={cowScore} stroke="#1482B0" strokeWidth={3} />

                    <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 chartHeight = yAxis.height
                        const chartBottom = chartTop + chartHeight
                        const [domainMin, domainMax] = xAxis.domain || [-2, 2]
                        const domainRange = domainMax - domainMin
                        const sigmaToX = (sigma: number) => chartX + ((sigma - domainMin) / domainRange) * chartWidth

                        const cowX = sigmaToX(cowScore)
                        const farmX = sigmaToX(farmScore)
                        const regionX = sigmaToX(regionScore)

                        return (
                          <g>
                            {/* 배지들 (위에서 아래로) */}
                            {/* 보은군 배지 */}
                            <rect x={regionX - 45} y={chartTop - 85} width={90} height={26} rx={5} fill="#2563eb" />
                            <text x={regionX} y={chartTop - 68} textAnchor="middle" fill="white" fontSize={12} fontWeight={700}>
                              보은군 +{regionScore.toFixed(2)}
                            </text>
                            <line x1={regionX} y1={chartTop - 59} x2={regionX} y2={chartTop} stroke="#2563eb" strokeWidth={1.5} strokeDasharray="3 2" />

                            {/* 농가 배지 */}
                            <rect x={farmX - 40} y={chartTop - 55} width={80} height={26} rx={5} fill="#f59e0b" />
                            <text x={farmX} y={chartTop - 38} textAnchor="middle" fill="white" fontSize={12} fontWeight={700}>
                              농가 +{farmScore.toFixed(2)}
                            </text>
                            <line x1={farmX} y1={chartTop - 29} x2={farmX} y2={chartTop} stroke="#f59e0b" strokeWidth={1.5} strokeDasharray="3 2" />

                            {/* 개체 배지 (가장 크게) */}
                            <rect x={cowX - 55} y={chartTop - 25} width={110} height={32} rx={6} fill="#1482B0" />
                            <text x={cowX} y={chartTop - 5} textAnchor="middle" fill="white" fontSize={14} fontWeight={700}>
                              내 개체 +{cowScore.toFixed(2)}
                            </text>

                            {/* 대비값 표시 (하단) */}
                            <rect x={chartX + chartWidth / 2 - 140} y={chartBottom + 15} width={280} height={40} rx={8} fill="#1e293b" />
                            <text x={chartX + chartWidth / 2} y={chartBottom + 30} textAnchor="middle" fill="white" fontSize={11}>
                              내 개체는
                            </text>
                            <text x={chartX + chartWidth / 2} y={chartBottom + 47} textAnchor="middle" fill="white" fontSize={13} fontWeight={700}>
                              <tspan fill="#fbbf24">농가보다 +{cowVsFarm.toFixed(2)}</tspan>
                              <tspan fill="#94a3b8"> | </tspan>
                              <tspan fill="#60a5fa">보은군보다 +{cowVsRegion.toFixed(2)}</tspan>
                              <tspan fill="white"> 높음</tspan>
                            </text>

                            {/* 화살표 */}
                            <defs>
                              <marker id="arrowFarmU" markerWidth="8" markerHeight="8" refX="0" refY="3" orient="auto">
                                <path d="M8,0 L8,6 L0,3 z" fill="#f59e0b" />
                              </marker>
                              <marker id="arrowRegionU" markerWidth="8" markerHeight="8" refX="0" refY="3" orient="auto">
                                <path d="M8,0 L8,6 L0,3 z" fill="#2563eb" />
                              </marker>
                            </defs>

                            {/* 농가 → 개체 화살표 */}
                            <line
                              x1={cowX}
                              y1={chartTop + chartHeight * 0.3}
                              x2={farmX + 8}
                              y2={chartTop + chartHeight * 0.3}
                              stroke="#f59e0b"
                              strokeWidth={2.5}
                              markerEnd="url(#arrowFarmU)"
                            />
                            <rect x={(cowX + farmX) / 2 - 35} y={chartTop + chartHeight * 0.3 - 24} width={70} height={20} rx={4} fill="#f59e0b" />
                            <text x={(cowX + farmX) / 2} y={chartTop + chartHeight * 0.3 - 10} textAnchor="middle" fill="white" fontSize={11} fontWeight={700}>
                              +{cowVsFarm.toFixed(2)}
                            </text>

                            {/* 보은군 → 개체 화살표 */}
                            <line
                              x1={cowX}
                              y1={chartTop + chartHeight * 0.5}
                              x2={regionX + 8}
                              y2={chartTop + chartHeight * 0.5}
                              stroke="#2563eb"
                              strokeWidth={2.5}
                              markerEnd="url(#arrowRegionU)"
                            />
                            <rect x={(cowX + regionX) / 2 - 35} y={chartTop + chartHeight * 0.5 - 24} width={70} height={20} rx={4} fill="#2563eb" />
                            <text x={(cowX + regionX) / 2} y={chartTop + chartHeight * 0.5 - 10} textAnchor="middle" fill="white" fontSize={11} fontWeight={700}>
                              +{cowVsRegion.toFixed(2)}
                            </text>
                          </g>
                        )
                      }}
                    />
                  </ComposedChart>
                </ResponsiveContainer>
              </div>
            </CardContent>
          </Card>
        )}

        {/* ============ 스택 차트 ============ */}
        {chartType === 'stack' && (
          <Card>
            <CardContent className="p-4">
              <h2 className="text-lg font-bold mb-2">스택 차트: 위아래로 2개 차트</h2>
              <p className="text-sm text-muted-foreground mb-4">
                클릭 없이 한눈에 농가/보은군 기준 모두 확인 가능
              </p>
              <div className="space-y-4">
                <MiniDistributionChart
                  title="농가 기준"
                  baseLabel="농가"
                  baseColor="#f59e0b"
                  bgColor="bg-amber-50"
                  borderColor="border-amber-300"
                  cowPosition={cowVsFarm}
                  histogramData={histogramData}
                />
                <MiniDistributionChart
                  title="보은군 기준"
                  baseLabel="보은군"
                  baseColor="#2563eb"
                  bgColor="bg-blue-50"
                  borderColor="border-blue-300"
                  cowPosition={cowVsRegion}
                  histogramData={histogramData}
                />
              </div>
              <div className="mt-4 p-4 bg-slate-100 rounded-xl">
                <div className="text-center">
                  <span className="text-lg font-bold text-foreground">요약: </span>
                  <span className="text-amber-600 font-bold">농가 대비 +{cowVsFarm.toFixed(2)}</span>
                  <span className="mx-2 text-muted-foreground">|</span>
                  <span className="text-blue-600 font-bold">보은군 대비 +{cowVsRegion.toFixed(2)}</span>
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        {/* ============ 듀얼 X축 차트 ============ */}
        {chartType === 'dual' && (
          <Card>
            <CardContent className="p-4">
              <h2 className="text-lg font-bold mb-2">듀얼 X축: 상단(농가) + 하단(보은군)</h2>
              <p className="text-sm text-muted-foreground mb-4">하나의 차트에서 두 기준을 동시에 확인</p>
              <div className="grid grid-cols-2 gap-3 mb-4">
                <div className="p-3 rounded-lg border-2 border-amber-400 bg-amber-50">
                  <div className="text-xs text-muted-foreground mb-1">농가 기준</div>
                  <div className={`text-xl font-bold ${cowVsFarm >= 0 ? 'text-green-600' : 'text-red-500'}`}>
                    {cowVsFarm >= 0 ? '+' : ''}{cowVsFarm.toFixed(2)}
                  </div>
                </div>
                <div className="p-3 rounded-lg border-2 border-blue-400 bg-blue-50">
                  <div className="text-xs text-muted-foreground mb-1">보은군 기준</div>
                  <div className={`text-xl font-bold ${cowVsRegion >= 0 ? 'text-green-600' : 'text-red-500'}`}>
                    {cowVsRegion >= 0 ? '+' : ''}{cowVsRegion.toFixed(2)}
                  </div>
                </div>
              </div>
              <div className="h-[350px] bg-slate-50 rounded-xl p-4">
                <ResponsiveContainer width="100%" height="100%">
                  <ComposedChart data={histogramData} margin={{ top: 55, right: 30, left: 10, bottom: 55 }}>
                    <defs>
                      <linearGradient id="areaGradient" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="0%" stopColor="#3b82f6" stopOpacity={0.4} />
                        <stop offset="100%" stopColor="#93c5fd" stopOpacity={0.1} />
                      </linearGradient>
                    </defs>
                    <XAxis
                      xAxisId="farm"
                      dataKey="midPoint"
                      type="number"
                      domain={[-2.5, 2.5]}
                      orientation="top"
                      tick={{ fontSize: 11, fill: '#d97706' }}
                      tickLine={{ stroke: '#f59e0b' }}
                      axisLine={{ stroke: '#f59e0b', strokeWidth: 2 }}
                      tickFormatter={(value) => {
                        const farmBased = value - farmScore
                        if (Math.abs(farmBased) < 0.01) return '농가'
                        return `${farmBased > 0 ? '+' : ''}${farmBased.toFixed(1)}`
                      }}
                    />
                    <XAxis
                      xAxisId="region"
                      dataKey="midPoint"
                      type="number"
                      domain={[-2.5, 2.5]}
                      orientation="bottom"
                      tick={{ fontSize: 11, fill: '#2563eb' }}
                      tickLine={{ stroke: '#3b82f6' }}
                      axisLine={{ stroke: '#3b82f6', strokeWidth: 2 }}
                      tickFormatter={(value) => {
                        const regionBased = value - regionScore
                        if (Math.abs(regionBased) < 0.01) return '보은군'
                        return `${regionBased > 0 ? '+' : ''}${regionBased.toFixed(1)}`
                      }}
                    />
                    <YAxis tick={{ fontSize: 10 }} width={30} tickFormatter={(v) => `${v}%`} />
                    <Area xAxisId="farm" type="natural" dataKey="percent" stroke="#3b82f6" strokeWidth={2} fill="url(#areaGradient)" />
                    <ReferenceLine xAxisId="farm" x={regionScore} stroke="#2563eb" strokeWidth={2} strokeDasharray="4 2" />
                    <ReferenceLine xAxisId="farm" x={farmScore} stroke="#f59e0b" strokeWidth={2} strokeDasharray="4 2" />
                    <ReferenceLine xAxisId="farm" x={cowScore} stroke="#1482B0" strokeWidth={3} />
                    <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 chartHeight = yAxis.height
                        const chartBottom = chartTop + chartHeight
                        const [domainMin, domainMax] = xAxis.domain || [-2.5, 2.5]
                        const domainRange = domainMax - domainMin
                        const sigmaToX = (sigma: number) => chartX + ((sigma - domainMin) / domainRange) * chartWidth
                        const cowX = sigmaToX(cowScore)
                        return (
                          <g>
                            <rect x={cowX - 45} y={chartTop - 42} width={90} height={20} rx={4} fill="#f59e0b" />
                            <text x={cowX} y={chartTop - 28} textAnchor="middle" fill="white" fontSize={11} fontWeight={700}>
                              농가 대비 +{cowVsFarm.toFixed(2)}
                            </text>
                            <rect x={cowX - 50} y={chartBottom + 8} width={100} height={20} rx={4} fill="#2563eb" />
                            <text x={cowX} y={chartBottom + 22} textAnchor="middle" fill="white" fontSize={11} fontWeight={700}>
                              보은군 대비 +{cowVsRegion.toFixed(2)}
                            </text>
                            <rect x={cowX - 35} y={chartTop + 15} width={70} height={22} rx={4} fill="#1482B0" />
                            <text x={cowX} y={chartTop + 30} textAnchor="middle" fill="white" fontSize={11} fontWeight={700}>내 개체</text>
                          </g>
                        )
                      }}
                    />
                  </ComposedChart>
                </ResponsiveContainer>
              </div>
            </CardContent>
          </Card>
        )}

        {/* ============ 단일 차트 (토글) ============ */}
        {chartType === 'single' && (
          <Card>
            <CardContent className="p-4">
              <h2 className="text-lg font-bold mb-2">단일 차트 (토글 방식)</h2>
              <p className="text-sm text-muted-foreground mb-4">버튼을 눌러 농가/보은군 기준 전환</p>
              <div className="flex gap-2 mb-4">
                <button
                  onClick={() => setViewMode('farm')}
                  className={`flex-1 py-3 rounded-lg font-bold transition-colors ${viewMode === 'farm' ? 'bg-amber-500 text-white' : 'bg-amber-100 text-amber-700 hover:bg-amber-200'}`}
                >
                  농가 기준
                </button>
                <button
                  onClick={() => setViewMode('region')}
                  className={`flex-1 py-3 rounded-lg font-bold transition-colors ${viewMode === 'region' ? 'bg-blue-500 text-white' : 'bg-blue-100 text-blue-700 hover:bg-blue-200'}`}
                >
                  보은군 기준
                </button>
              </div>
              <MiniDistributionChart
                title={viewMode === 'farm' ? '농가 기준' : '보은군 기준'}
                baseLabel={viewMode === 'farm' ? '농가' : '보은군'}
                baseColor={viewMode === 'farm' ? '#f59e0b' : '#2563eb'}
                bgColor={viewMode === 'farm' ? 'bg-amber-50' : 'bg-blue-50'}
                borderColor={viewMode === 'farm' ? 'border-amber-300' : 'border-blue-300'}
                cowPosition={viewMode === 'farm' ? cowVsFarm : cowVsRegion}
                histogramData={histogramData}
              />
            </CardContent>
          </Card>
        )}

        {/* 비교 설명 */}
        <Card>
          <CardContent className="p-4">
            <h2 className="text-lg font-bold mb-3">방식 비교</h2>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
              <div className="p-3 bg-green-50 border-2 border-green-300 rounded-lg col-span-1 sm:col-span-2">
                <strong className="text-green-700">내 개체 중심 (추천)</strong>
                <p className="text-muted-foreground mt-1">내 개체를 오른쪽에 고정, 농가/보은군 평균이 왼쪽에 표시. "오른쪽 = 좋음"으로 직관적. 한 차트에 두 기준 모두 표시.</p>
              </div>
              <div className="p-3 bg-slate-50 border border-slate-200 rounded-lg">
                <strong className="text-slate-700">오버레이</strong>
                <p className="text-muted-foreground mt-1">농가/보은군 기준 정규분포를 겹쳐서 한 차트에 표시.</p>
              </div>
              <div className="p-3 bg-slate-50 border border-slate-200 rounded-lg">
                <strong className="text-slate-700">개체 중심(구)</strong>
                <p className="text-muted-foreground mt-1">이전 버전의 개체 중심 차트.</p>
              </div>
              <div className="p-3 bg-slate-50 border border-slate-200 rounded-lg">
                <strong className="text-slate-700">막대 비교</strong>
                <p className="text-muted-foreground mt-1">정규분포 없이 단순 막대로 비교. 가장 직관적이고 이해하기 쉬움.</p>
              </div>
              <div className="p-3 bg-slate-50 border border-slate-200 rounded-lg">
                <strong className="text-slate-700">통합 차트</strong>
                <p className="text-muted-foreground mt-1">전국 기준 정규분포에 3개 마커. 대비값은 보이지만 기준이 전국.</p>
              </div>
              <div className="p-3 bg-slate-50 border border-slate-200 rounded-lg">
                <strong className="text-slate-700">스택 차트</strong>
                <p className="text-muted-foreground mt-1">위아래로 2개 차트. 클릭 없이 두 기준 비교 가능.</p>
              </div>
              <div className="p-3 bg-slate-50 border border-slate-200 rounded-lg">
                <strong className="text-slate-700">듀얼 X축</strong>
                <p className="text-muted-foreground mt-1">하나의 차트에 X축 2개. 공간 효율적이지만 복잡.</p>
              </div>
              <div className="p-3 bg-slate-50 border border-slate-200 rounded-lg col-span-1 sm:col-span-2">
                <strong className="text-slate-700">토글 방식</strong>
                <p className="text-muted-foreground mt-1">현재 방식. 버튼 눌러야 다른 기준 볼 수 있음.</p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
