import React, { useMemo, useState, useRef, useEffect, useCallback } from 'react';
import {
  Box,
  Typography,
  IconButton,
  Chip,
  useTheme,
  Paper,
  Slider,
} from '@mui/material';
import { Close, DragIndicator, Minimize, OpenInFull, ZoomIn, ZoomOut } from '@mui/icons-material';
import {
  ComposedChart,
  Line,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  ReferenceLine,
  Cell,
  Area,
} from 'recharts';
import { MacdResult } from '../types/stock';
import { format, parseISO } from 'date-fns';
import { useChartColors } from '../contexts/ChartColorContext';
import { useIndicatorVisibility } from '../contexts/IndicatorVisibilityContext';
import { useIndicatorSettings } from '../contexts/IndicatorSettingsContext';

// 차트 타입 정의 (15가지 보조지표 + 캔들 + 거래량)
export type ChartDetailType = 'candle' | 'macd' | 'stochastic' | 'rsi' | 'adx' | 'cci' | 'trix' | 'volume' | 'disparity' | 'newPsychological' | 'investPsychological' | 'bwi' | 'dmi' | 'obv' | 'williamsR' | 'volumeOsc' | 'vr';

interface ChartDetailPopupProps {
  open: boolean;
  onClose: () => void;
  data: MacdResult[];
  centerIndex: number;  // 중심이 될 데이터 인덱스
  chartType: ChartDetailType;
  range?: number;  // 전후 표시할 캔들 수 (기본 5개)
  signal?: 'BUY' | 'SELL' | null;  // 매매 신호
  interval?: string;
}

const ChartDetailPopup: React.FC<ChartDetailPopupProps> = ({
  open,
  onClose,
  data,
  centerIndex,
  chartType,
  range: initialRange = 5,
  signal,
  interval = '1d',
}) => {
  const theme = useTheme();
  const isDark = theme.palette.mode === 'dark';
  const { colors } = useChartColors();
  const { settings } = useIndicatorVisibility();
  const { indicatorSettings } = useIndicatorSettings();
  
  // 줌 상태 (표시할 캔들 범위)
  const [zoomRange, setZoomRange] = useState(initialRange);
  const MIN_RANGE = 2;
  const MAX_RANGE = 20;
  
  // 드래그 상태
  const [position, setPosition] = useState({ x: 20, y: 100 });
  const [isDragging, setIsDragging] = useState(false);
  const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
  const [isMinimized, setIsMinimized] = useState(false);
  const popupRef = useRef<HTMLDivElement>(null);
  const chartAreaRef = useRef<HTMLDivElement>(null);
  
  // 투명도 상태 (0 = 완전 투명, 100 = 불투명)
  const [opacity, setOpacity] = useState(100);

  // 팝업 크기 (정사각형)
  const POPUP_SIZE = 500;
  const MINIMIZED_SIZE = 280;

  // 초기 위치 설정 (우측 상단)
  useEffect(() => {
    if (open && popupRef.current) {
      const windowWidth = window.innerWidth;
      setPosition({ x: windowWidth - POPUP_SIZE - 20, y: 80 });
      setZoomRange(initialRange);
    }
  }, [open, initialRange]);

  // 드래그 핸들러
  const handleMouseDown = (e: React.MouseEvent) => {
    if (popupRef.current) {
      const rect = popupRef.current.getBoundingClientRect();
      setDragOffset({
        x: e.clientX - rect.left,
        y: e.clientY - rect.top,
      });
      setIsDragging(true);
    }
  };

  const handleMouseMove = useCallback((e: MouseEvent) => {
    if (isDragging && popupRef.current) {
      // 새 위치 계산
      let newX = e.clientX - dragOffset.x;
      let newY = e.clientY - dragOffset.y;
      
      // 상단만 제한 (0보다 작아지지 않도록)
      const minY = 0;
      newY = Math.max(minY, newY);
      
      setPosition({
        x: newX,
        y: newY,
      });
    }
  }, [isDragging, dragOffset]);

  const handleMouseUp = useCallback(() => {
    setIsDragging(false);
  }, []);

  useEffect(() => {
    if (isDragging) {
      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
    }
    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    };
  }, [isDragging, handleMouseMove, handleMouseUp]);

  // 마우스 휠 줌 핸들러
  const handleWheel = useCallback((e: WheelEvent) => {
    e.preventDefault();
    e.stopPropagation();
    
    setZoomRange(prev => {
      if (e.deltaY > 0) {
        // 줌 아웃 (더 많은 캔들 표시)
        return Math.min(prev + 1, MAX_RANGE);
      } else {
        // 줌 인 (더 적은 캔들 표시)
        return Math.max(prev - 1, MIN_RANGE);
      }
    });
  }, []);

  // 차트 영역에 휠 이벤트 리스너 추가
  useEffect(() => {
    const chartArea = chartAreaRef.current;
    if (chartArea && open) {
      chartArea.addEventListener('wheel', handleWheel, { passive: false });
    }
    return () => {
      if (chartArea) {
        chartArea.removeEventListener('wheel', handleWheel);
      }
    };
  }, [open, handleWheel]);

  // SMA 계산 함수
  const calculateSMA = useMemo(() => {
    return (period: number): (number | null)[] => {
      const ma: (number | null)[] = [];
      for (let i = 0; i < data.length; i++) {
        if (i < period - 1) {
          ma.push(null);
        } else {
          let sum = 0;
          for (let j = i - period + 1; j <= i; j++) {
            sum += data[j]?.close || 0;
          }
          ma.push(sum / period);
        }
      }
      return ma;
    };
  }, [data]);

  // EMA 계산 함수
  const calculateEMA = useMemo(() => {
    return (period: number): (number | null)[] => {
      const ema: (number | null)[] = [];
      const multiplier = 2 / (period + 1);
      
      for (let i = 0; i < data.length; i++) {
        if (i < period - 1) {
          ema.push(null);
        } else if (i === period - 1) {
          // 첫 EMA는 SMA로 계산
          let sum = 0;
          for (let j = 0; j < period; j++) {
            sum += data[i - j]?.close || 0;
          }
          ema.push(sum / period);
        } else {
          const prevEMA = ema[i - 1];
          if (prevEMA !== null) {
            const currentClose = data[i]?.close || 0;
            ema.push((currentClose - prevEMA) * multiplier + prevEMA);
          } else {
            ema.push(null);
          }
        }
      }
      return ema;
    };
  }, [data]);

  // 이동평균선 데이터 사전 계산 (maLines 설정 기반)
  const maData = useMemo(() => {
    const result: { [key: string]: (number | null)[] } = {};
    
    // settings.maLines 기반으로 계산
    if (settings.maLines) {
      settings.maLines.forEach(maConfig => {
        const key = `customMA_${maConfig.period}_${maConfig.type}`;
        if (maConfig.type === 'EMA') {
          result[key] = calculateEMA(maConfig.period);
        } else {
          result[key] = calculateSMA(maConfig.period);
        }
      });
    }
    
    return result;
  }, [calculateSMA, calculateEMA, settings.maLines]);

  // 신규 보조지표 계산 함수들
  const calculateIndicators = useMemo(() => {
    // 1. 신심리도/투자심리도 계산
    const calcPsychological = (period: number): (number | null)[] => {
      const result: (number | null)[] = [];
      for (let i = 0; i < data.length; i++) {
        if (i < period) { result.push(null); continue; }
        let upDays = 0;
        for (let j = 0; j < period; j++) {
          if (data[i - j].close > (data[i - j - 1]?.close || 0)) upDays++;
        }
        result.push((upDays / period) * 100);
      }
      return result;
    };
    
    // 2. BWI 계산
    const calcBWI = (period: number = 20): (number | null)[] => {
      const result: (number | null)[] = [];
      for (let i = 0; i < data.length; i++) {
        if (i < period - 1) { result.push(null); continue; }
        let sum = 0;
        for (let j = 0; j < period; j++) sum += data[i - j].close;
        const middle = sum / period;
        let variance = 0;
        for (let j = 0; j < period; j++) variance += Math.pow(data[i - j].close - middle, 2);
        const std = Math.sqrt(variance / period);
        const upper = middle + 2 * std;
        const lower = middle - 2 * std;
        result.push(middle > 0 ? ((upper - lower) / middle) * 100 : null);
      }
      return result;
    };
    
    // 3. OBV 계산
    const calcOBV = (): (number | null)[] => {
      const result: (number | null)[] = [];
      let obv = 0;
      for (let i = 0; i < data.length; i++) {
        if (i === 0) { obv = data[i].volume || 0; }
        else {
          const vol = data[i].volume || 0;
          if (data[i].close > data[i - 1].close) obv += vol;
          else if (data[i].close < data[i - 1].close) obv -= vol;
        }
        result.push(obv);
      }
      return result;
    };
    
    // 4. Williams %R 계산
    const calcWilliamsR = (period: number = 14): (number | null)[] => {
      const result: (number | null)[] = [];
      for (let i = 0; i < data.length; i++) {
        if (i < period - 1) { result.push(null); continue; }
        let hh = -Infinity, ll = Infinity;
        for (let j = 0; j < period; j++) {
          hh = Math.max(hh, data[i - j].high ?? data[i - j].close);
          ll = Math.min(ll, data[i - j].low ?? data[i - j].close);
        }
        const range = hh - ll;
        result.push(range === 0 ? -50 : ((hh - data[i].close) / range) * -100);
      }
      return result;
    };
    
    // 5. VolumeOSC 계산
    const calcVolumeOSC = (short: number = 10, long: number = 20): (number | null)[] => {
      const result: (number | null)[] = [];
      const calcVolMA = (p: number) => {
        const ma: (number | null)[] = [];
        for (let i = 0; i < data.length; i++) {
          if (i < p - 1) { ma.push(null); continue; }
          let sum = 0;
          for (let j = 0; j < p; j++) sum += data[i - j].volume || 0;
          ma.push(sum / p);
        }
        return ma;
      };
      const shortMA = calcVolMA(short);
      const longMA = calcVolMA(long);
      for (let i = 0; i < data.length; i++) {
        if (shortMA[i] == null || longMA[i] == null || longMA[i] === 0) result.push(null);
        else result.push(((shortMA[i]! - longMA[i]!) / longMA[i]!) * 100);
      }
      return result;
    };
    
    // 6. VR 계산
    const calcVR = (period: number = 10): (number | null)[] => {
      const result: (number | null)[] = [];
      for (let i = 0; i < data.length; i++) {
        if (i < period) { result.push(null); continue; }
        let upVol = 0, downVol = 0, neutVol = 0;
        for (let j = 0; j < period; j++) {
          const idx = i - j;
          const vol = data[idx].volume || 0;
          if (data[idx].close > (data[idx - 1]?.close || 0)) upVol += vol;
          else if (data[idx].close < (data[idx - 1]?.close || 0)) downVol += vol;
          else neutVol += vol;
        }
        const num = upVol + neutVol / 2;
        const den = downVol + neutVol / 2;
        result.push(den === 0 ? null : (num / den) * 100);
      }
      return result;
    };
    
    return {
      newPsychological: calcPsychological(5),
      investPsychological: calcPsychological(10),
      bwi: calcBWI(20),
      obv: calcOBV(),
      williamsR: calcWilliamsR(14),
      volumeOsc: calcVolumeOSC(10, 20),
      vr: calcVR(10),
    };
  }, [data]);

  // 중심 인덱스 기준으로 전후 range 개의 데이터 추출
  const detailData = useMemo(() => {
    if (!data || data.length === 0 || centerIndex < 0) return [];
    
    const startIdx = Math.max(0, centerIndex - zoomRange);
    const endIdx = Math.min(data.length - 1, centerIndex + zoomRange);
    
    // 이격도 계산 (20일 SMA 기준)
    const calculateDisparity = (index: number): number | null => {
      // maLines에서 20일 SMA 찾기
      const ma20Key = 'customMA_20_SMA';
      const ma20Val = maData[ma20Key]?.[index];
      if (ma20Val == null || ma20Val <= 0) return null;
      return (data[index]?.close || 0) / ma20Val * 100;
    };
    
    return data.slice(startIdx, endIdx + 1).map((item, idx) => {
      const absoluteIndex = startIdx + idx;
      // 이격도: item에 있으면 사용, 없으면 계산
      const disparity = item.disparity ?? calculateDisparity(absoluteIndex);
      
      // maLines 기반 MA 데이터 추가
      const customMAValues: { [key: string]: number | null } = {};
      if (settings.maLines) {
        settings.maLines.forEach(maConfig => {
          const key = `customMA_${maConfig.period}_${maConfig.type}`;
          customMAValues[key] = maData[key]?.[absoluteIndex] ?? null;
        });
      }
      
      return {
        ...item,
        // maLines 기반 이동평균선 데이터 추가
        ...customMAValues,
        // 이격도 추가
        disparity,
        // 신규 보조지표 추가 (item에 있으면 사용, 없으면 계산된 값 사용)
        newPsychological: item.newPsychological ?? calculateIndicators.newPsychological[absoluteIndex],
        investPsychological: item.investPsychological ?? calculateIndicators.investPsychological[absoluteIndex],
        bwi: item.bwi ?? calculateIndicators.bwi[absoluteIndex],
        obv: item.obv ?? calculateIndicators.obv[absoluteIndex],
        williamsR: item.williamsR ?? calculateIndicators.williamsR[absoluteIndex],
        volumeOsc: item.volumeOsc ?? calculateIndicators.volumeOsc[absoluteIndex],
        vr: item.vr ?? calculateIndicators.vr[absoluteIndex],
        // CCI는 cci13 필드 호환성 유지
        cci: item.cci ?? item.cci13,
        isCenter: absoluteIndex === centerIndex,
        displayDate: formatDate(item, interval),
      };
    });
  }, [data, centerIndex, zoomRange, interval, maData, calculateIndicators, settings.maLines]);

  // RSI, CCI, OBV Signal 계산 (SMA 기반) - 전체 데이터 기준으로 계산
  const calculateSignal = useCallback((values: (number | null | undefined)[], period: number): (number | null)[] => {
    const result: (number | null)[] = [];
    for (let i = 0; i < values.length; i++) {
      if (values[i] === null || values[i] === undefined || i < period - 1) {
        result.push(null);
        continue;
      }
      let sum = 0;
      let count = 0;
      for (let j = 0; j < period; j++) {
        const val = values[i - j];
        if (val !== null && val !== undefined) {
          sum += val;
          count++;
        }
      }
      result.push(count === period ? sum / period : null);
    }
    return result;
  }, []);

  // 전체 데이터에서 신호선 계산 (detailData가 아닌 전체 data 기준)
  const fullSignalData = useMemo(() => {
    if (!data || data.length === 0) return { rsiSignal: [], cciSignal: [], obvSignal: [] };
    
    const rsiValues = data.map(d => d.rsi);
    const cciValues = data.map(d => (d.cci ?? d.cci13));
    // OBV는 원시 데이터에 없을 수 있으므로 calculateIndicators에서 계산된 값 사용
    const obvValues = data.map((d, i) => d.obv ?? calculateIndicators.obv[i]);
    
    return {
      rsiSignal: calculateSignal(rsiValues, indicatorSettings.rsiSignalPeriod || 9),
      cciSignal: calculateSignal(cciValues, indicatorSettings.cciSignalPeriod || 10),
      obvSignal: calculateSignal(obvValues, indicatorSettings.obvSignalPeriod || 9),
    };
  }, [data, calculateSignal, calculateIndicators.obv, indicatorSettings.rsiSignalPeriod, indicatorSettings.cciSignalPeriod, indicatorSettings.obvSignalPeriod]);

  // detailData에 신호선 데이터 추가 (전체 데이터에서 계산된 신호값 사용)
  const detailDataWithSignals = useMemo(() => {
    if (!data || data.length === 0 || centerIndex < 0) return [];
    
    const startIdx = Math.max(0, centerIndex - zoomRange);
    
    return detailData.map((item, idx) => {
      const absoluteIndex = startIdx + idx;
      return {
        ...item,
        rsiSignal: fullSignalData.rsiSignal[absoluteIndex],
        cciSignal: fullSignalData.cciSignal[absoluteIndex],
        obvSignal: fullSignalData.obvSignal[absoluteIndex],
      };
    });
  }, [detailData, fullSignalData, data, centerIndex, zoomRange]);

  // 날짜 포맷
  function formatDate(item: MacdResult, interval: string): string {
    try {
      const dateStr = item.timestamp || item.date;
      if (!dateStr) return '-';
      const date = parseISO(dateStr);
      
      if (interval.endsWith('m') || interval.endsWith('h')) {
        return format(date, 'HH:mm');
      }
      return format(date, 'MM/dd');
    } catch {
      return '-';
    }
  }

  // 차트 타입별 제목
  const getChartTitle = (): string => {
    switch (chartType) {
      case 'candle': return '캔들 상세';
      case 'macd': return 'MACD';
      case 'stochastic': return 'Stochastic';
      case 'rsi': return 'RSI';
      case 'adx': return 'ADX';
      case 'cci': return 'CCI';
      case 'trix': return 'TRIX';
      case 'volume': return '거래량';
      case 'disparity': return '이격도';
      case 'newPsychological': return '신심리도';
      case 'investPsychological': return '투자심리도';
      case 'bwi': return 'BWI';
      case 'dmi': return 'DMI';
      case 'obv': return 'OBV';
      case 'williamsR': return 'Williams %R';
      case 'volumeOsc': return 'VolumeOSC';
      case 'vr': return 'VR';
      default: return '차트 상세';
    }
  };

  // 차트 타입별 아이콘
  const getChartIcon = (): string => {
    switch (chartType) {
      case 'candle': return '🕯️';
      case 'macd': return '📊';
      case 'stochastic': return '📈';
      case 'rsi': return '📉';
      case 'adx': return '📐';
      case 'cci': return '〰️';
      case 'trix': return '🔀';
      case 'volume': return '📦';
      case 'disparity': return '📏';
      case 'newPsychological': return '🧠';
      case 'investPsychological': return '💭';
      case 'bwi': return '📐';
      case 'dmi': return '↕️';
      case 'obv': return '📊';
      case 'williamsR': return '📉';
      case 'volumeOsc': return '📶';
      case 'vr': return '⚖️';
      default: return '📊';
    }
  };

  // 중심 데이터 정보
  const centerData = data[centerIndex];

  // 차트 높이 계산 (정사각형에 맞춰 더 크게)
  const chartHeight = isMinimized ? 150 : 380;

  // 캔들스틱 렌더러
  const renderCandlestick = (props: any): React.ReactElement => {
    const { x, y, width, height, payload } = props;
    if (!payload) return <g />;

    const { open, close, high, low, isCenter } = payload;
    const isUp = close >= open;
    // 시인성 좋은 밝은 색상: 상향(빨간색), 하향(파란색)
    const upColor = '#ff5252';   // 밝은 빨간색
    const downColor = '#448aff'; // 밝은 파란색
    const color = isUp ? upColor : downColor;
    
    const candleWidth = Math.max(width * 0.7, 6);
    const candleX = x + (width - candleWidth) / 2;
    
    // 가격 범위 계산
    const priceRange = Math.max(...detailDataWithSignals.map(d => d.high || 0)) - Math.min(...detailDataWithSignals.map(d => d.low || Infinity));
    const yScale = chartHeight / priceRange;
    const minPrice = Math.min(...detailDataWithSignals.map(d => d.low || Infinity));
    
    const bodyTop = Math.max(open, close);
    const bodyBottom = Math.min(open, close);
    const bodyHeight = Math.max((bodyTop - bodyBottom) * yScale, 1);
    const bodyY = chartHeight - (bodyTop - minPrice) * yScale + 20;
    
    const wickX = x + width / 2;
    const wickTop = chartHeight - (high - minPrice) * yScale + 20;
    const wickBottom = chartHeight - (low - minPrice) * yScale + 20;

    return (
      <g>
        {/* 중심 표시 배경 */}
        {isCenter && (
          <rect
            x={x}
            y={0}
            width={width}
            height={chartHeight + 40}
            fill={signal === 'BUY' ? 'rgba(34, 197, 94, 0.15)' : signal === 'SELL' ? 'rgba(239, 68, 68, 0.15)' : 'rgba(99, 102, 241, 0.1)'}
          />
        )}
        {/* 심지 */}
        <line
          x1={wickX}
          y1={wickTop}
          x2={wickX}
          y2={wickBottom}
          stroke={color}
          strokeWidth={1.5}
        />
        {/* 몸통 */}
        <rect
          x={candleX}
          y={bodyY}
          width={candleWidth}
          height={bodyHeight}
          fill={color}
          stroke={color}
          strokeWidth={1.5}
        />
        {/* 중심점 마커 */}
        {isCenter && signal && (
          <circle
            cx={wickX}
            cy={signal === 'BUY' ? wickBottom + 12 : wickTop - 12}
            r={6}
            fill={signal === 'BUY' ? '#22c55e' : '#ef4444'}
            stroke="#fff"
            strokeWidth={2}
          />
        )}
      </g>
    );
  };

  // 줌 버튼 핸들러
  const handleZoomIn = () => {
    setZoomRange(prev => Math.max(prev - 1, MIN_RANGE));
  };

  const handleZoomOut = () => {
    setZoomRange(prev => Math.min(prev + 1, MAX_RANGE));
  };

  // 차트 렌더링
  const renderChart = () => {
    if (detailDataWithSignals.length === 0) return null;

    const commonProps = {
      data: detailDataWithSignals,
      margin: { top: 20, right: 0, left: 10, bottom: 20 },
    };

    switch (chartType) {
      case 'candle':
        return (
          <Box sx={{ height: chartHeight, position: 'relative' }}>
            <ResponsiveContainer width="100%" height="100%">
              <ComposedChart {...commonProps}>
                <CartesianGrid strokeDasharray="3 3" stroke={isDark ? '#2d3748' : '#e0e0e0'} />
                <XAxis 
                  dataKey="displayDate" 
                  tick={{ fontSize: 11, fill: isDark ? '#a0aec0' : '#666' }}
                  stroke={isDark ? '#4a5568' : '#ccc'}
                />
                <YAxis 
                  domain={['auto', 'auto']}
                  hide={true}
                  width={0}
                />
                <Tooltip
                  contentStyle={{
                    backgroundColor: isDark ? '#1a1a2e' : '#fff',
                    border: `1px solid ${isDark ? '#333' : '#ddd'}`,
                    borderRadius: 6,
                    fontSize: 12,
                  }}
                  formatter={(value: any, name: string) => {
                    if (name === 'close') return [`${value?.toLocaleString()}원`, '종가'];
                    if (name === 'open') return [`${value?.toLocaleString()}원`, '시가'];
                    if (name === 'high') return [`${value?.toLocaleString()}원`, '고가'];
                    if (name === 'low') return [`${value?.toLocaleString()}원`, '저가'];
                    // maLines 기반 이동평균선 (예: MA10(SMA10), MA20(EMA20) 등)
                    if (name.startsWith('MA') || name.startsWith('EMA')) {
                      return [`${value?.toLocaleString()}`, name];
                    }
                    return [value, name];
                  }}
                />
                <Bar dataKey="close" shape={renderCandlestick} />
                {/* 이동평균선 - maLines 설정 기반으로 활성화된 것만 표시 */}
                {settings.maLines?.filter(ma => ma.enabled).map((ma) => (
                  <Line
                    key={ma.id}
                    type="monotone"
                    dataKey={`customMA_${ma.period}_${ma.type}`}
                    stroke={ma.color}
                    strokeWidth={ma.width}
                    dot={false}
                    name={`${ma.id}(${ma.type}${ma.period})`}
                    connectNulls
                  />
                ))}
              </ComposedChart>
            </ResponsiveContainer>
          </Box>
        );

      case 'macd':
        return (
          <Box sx={{ height: chartHeight }}>
            <ResponsiveContainer width="100%" height="100%">
              <ComposedChart {...commonProps}>
                <CartesianGrid strokeDasharray="3 3" stroke={isDark ? '#2d3748' : '#e0e0e0'} />
                <XAxis 
                  dataKey="displayDate" 
                  tick={{ fontSize: 11, fill: isDark ? '#a0aec0' : '#666' }}
                  stroke={isDark ? '#4a5568' : '#ccc'}
                />
                <YAxis 
                  domain={['auto', 'auto']}
                  hide={true}
                  width={0}
                />
                <Tooltip
                  contentStyle={{
                    backgroundColor: isDark ? '#1a1a2e' : '#fff',
                    border: `1px solid ${isDark ? '#333' : '#ddd'}`,
                    borderRadius: 6,
                    fontSize: 12,
                  }}
                  formatter={(value: any, name: string) => {
                    if (name === 'macdLine') return [value?.toFixed(2), 'MACD'];
                    if (name === 'signalLine') return [value?.toFixed(2), 'Signal'];
                    if (name === 'macdHistogram') return [value?.toFixed(2), 'Histogram'];
                    return [value, name];
                  }}
                />
                <ReferenceLine y={0} stroke="#666" strokeDasharray="3 3" />
                {/* 히스토그램 */}
                <Bar dataKey="macdHistogram" name="macdHistogram">
                  {detailDataWithSignals.map((entry, index) => (
                    <Cell 
                      key={`cell-${index}`} 
                      fill={(entry.macdHistogram || 0) >= 0 ? '#22c55e' : '#ef4444'}
                      opacity={entry.isCenter ? 1 : 0.6}
                    />
                  ))}
                </Bar>
                {/* MACD 라인 */}
                <Line 
                  type="monotone" 
                  dataKey="macdLine" 
                  stroke={colors.macdLine} 
                  strokeWidth={2.5}
                  dot={(props: any) => {
                    const { cx, cy, payload } = props;
                    if (payload?.isCenter) {
                      return (
                        <circle cx={cx} cy={cy} r={6} fill={colors.macdLine} stroke="#fff" strokeWidth={2} />
                      );
                    }
                    return <circle cx={cx} cy={cy} r={3} fill={colors.macdLine} />;
                  }}
                />
                {/* Signal 라인 */}
                <Line 
                  type="monotone" 
                  dataKey="signalLine" 
                  stroke={colors.signalLine} 
                  strokeWidth={2.5}
                  dot={(props: any) => {
                    const { cx, cy, payload } = props;
                    if (payload?.isCenter) {
                      return (
                        <circle cx={cx} cy={cy} r={6} fill={colors.signalLine} stroke="#fff" strokeWidth={2} />
                      );
                    }
                    return <circle cx={cx} cy={cy} r={3} fill={colors.signalLine} />;
                  }}
                />
              </ComposedChart>
            </ResponsiveContainer>
          </Box>
        );

      case 'stochastic':
        return (
          <Box sx={{ height: chartHeight }}>
            <ResponsiveContainer width="100%" height="100%">
              <ComposedChart {...commonProps}>
                <CartesianGrid strokeDasharray="3 3" stroke={isDark ? '#2d3748' : '#e0e0e0'} />
                <XAxis 
                  dataKey="displayDate" 
                  tick={{ fontSize: 11, fill: isDark ? '#a0aec0' : '#666' }}
                />
                <YAxis 
                  domain={[0, 100]}
                  hide={true}
                  width={0}
                />
                <Tooltip
                  contentStyle={{
                    backgroundColor: isDark ? '#1a1a2e' : '#fff',
                    border: `1px solid ${isDark ? '#333' : '#ddd'}`,
                    borderRadius: 6,
                    fontSize: 12,
                  }}
                  formatter={(value: any, name: string) => {
                    if (name === 'stochasticK') return [value?.toFixed(2), '%K'];
                    if (name === 'stochasticD') return [value?.toFixed(2), '%D'];
                    return [value, name];
                  }}
                />
                <ReferenceLine y={80} stroke="#ef4444" strokeDasharray="3 3" strokeWidth={1.5} />
                <ReferenceLine y={20} stroke="#22c55e" strokeDasharray="3 3" strokeWidth={1.5} />
                <Line 
                  type="monotone" 
                  dataKey="stochasticK" 
                  stroke={colors.stochasticK} 
                  strokeWidth={2.5}
                  dot={(props: any) => {
                    const { cx, cy, payload } = props;
                    if (payload?.isCenter) {
                      return <circle cx={cx} cy={cy} r={6} fill={colors.stochasticK} stroke="#fff" strokeWidth={2} />;
                    }
                    return <circle cx={cx} cy={cy} r={3} fill={colors.stochasticK} />;
                  }}
                />
                <Line 
                  type="monotone" 
                  dataKey="stochasticD" 
                  stroke={colors.stochasticD} 
                  strokeWidth={2.5}
                  dot={(props: any) => {
                    const { cx, cy, payload } = props;
                    if (payload?.isCenter) {
                      return <circle cx={cx} cy={cy} r={6} fill={colors.stochasticD} stroke="#fff" strokeWidth={2} />;
                    }
                    return <circle cx={cx} cy={cy} r={3} fill={colors.stochasticD} />;
                  }}
                />
              </ComposedChart>
            </ResponsiveContainer>
          </Box>
        );

      case 'rsi':
        return (
          <Box sx={{ height: chartHeight }}>
            <ResponsiveContainer width="100%" height="100%">
              <ComposedChart {...commonProps}>
                <CartesianGrid strokeDasharray="3 3" stroke={isDark ? '#2d3748' : '#e0e0e0'} />
                <XAxis dataKey="displayDate" tick={{ fontSize: 11, fill: isDark ? '#a0aec0' : '#666' }} />
                <YAxis domain={[0, 100]} hide={true} width={0} />
                <Tooltip
                  contentStyle={{
                    backgroundColor: isDark ? '#1a1a2e' : '#fff',
                    border: `1px solid ${isDark ? '#333' : '#ddd'}`,
                    borderRadius: 6,
                    fontSize: 12,
                  }}
                  formatter={(value: any, name: string) => [value?.toFixed(2), name === 'rsiSignal' ? 'Signal' : 'RSI']}
                />
                <ReferenceLine y={indicatorSettings.rsiOverbought || 70} stroke="#ef4444" strokeDasharray="3 3" strokeWidth={1.5} />
                <ReferenceLine y={indicatorSettings.rsiOversold || 30} stroke="#22c55e" strokeDasharray="3 3" strokeWidth={1.5} />
                <Area type="monotone" dataKey="rsi" fill="rgba(139, 92, 246, 0.2)" stroke="none" />
                <Line 
                  type="monotone" 
                  dataKey="rsi" 
                  stroke={colors.rsiColor || '#8b5cf6'} 
                  strokeWidth={colors.rsiWidth || 2.5}
                  dot={(props: any) => {
                    const { cx, cy, payload } = props;
                    if (payload?.isCenter) {
                      return <circle cx={cx} cy={cy} r={6} fill={colors.rsiColor || '#8b5cf6'} stroke="#fff" strokeWidth={2} />;
                    }
                    return <circle cx={cx} cy={cy} r={3} fill={colors.rsiColor || '#8b5cf6'} />;
                  }}
                />
                {/* RSI Signal 라인 */}
                {indicatorSettings.rsiSignalEnabled && (
                  <Line 
                    type="monotone" 
                    dataKey="rsiSignal" 
                    stroke={colors.rsiSignalColor || '#FF7043'} 
                    strokeWidth={colors.rsiSignalWidth || 1}
                    strokeDasharray="3 3"
                    dot={false}
                  />
                )}
              </ComposedChart>
            </ResponsiveContainer>
          </Box>
        );

      case 'adx':
        return (
          <Box sx={{ height: chartHeight }}>
            <ResponsiveContainer width="100%" height="100%">
              <ComposedChart {...commonProps}>
                <CartesianGrid strokeDasharray="3 3" stroke={isDark ? '#2d3748' : '#e0e0e0'} />
                <XAxis dataKey="displayDate" tick={{ fontSize: 11, fill: isDark ? '#a0aec0' : '#666' }} />
                <YAxis domain={[0, 100]} hide={true} width={0} />
                <Tooltip
                  contentStyle={{
                    backgroundColor: isDark ? '#1a1a2e' : '#fff',
                    border: `1px solid ${isDark ? '#333' : '#ddd'}`,
                    borderRadius: 6,
                    fontSize: 12,
                  }}
                  formatter={(value: any, name: string) => {
                    if (name === 'adx') return [value?.toFixed(2), 'ADX'];
                    if (name === 'plusDI') return [value?.toFixed(2), '+DI'];
                    if (name === 'minusDI') return [value?.toFixed(2), '-DI'];
                    return [value?.toFixed(2), name];
                  }}
                />
                <ReferenceLine y={25} stroke="#666" strokeDasharray="3 3" strokeWidth={1} />
                {/* ADX 라인 */}
                <Line 
                  type="monotone" 
                  dataKey="adx" 
                  stroke="#FFD54F" 
                  strokeWidth={2.5}
                  dot={(props: any) => {
                    const { cx, cy, payload } = props;
                    if (payload?.isCenter) {
                      return <circle cx={cx} cy={cy} r={6} fill="#FFD54F" stroke="#fff" strokeWidth={2} />;
                    }
                    return <circle cx={cx} cy={cy} r={3} fill="#FFD54F" />;
                  }}
                />
                {/* +DI 라인 */}
                <Line 
                  type="monotone" 
                  dataKey="plusDI" 
                  stroke="#26a69a" 
                  strokeWidth={1.5}
                  dot={(props: any) => {
                    const { cx, cy, payload } = props;
                    if (payload?.isCenter) {
                      return <circle cx={cx} cy={cy} r={5} fill="#26a69a" stroke="#fff" strokeWidth={1.5} />;
                    }
                    return <circle cx={cx} cy={cy} r={2} fill="#26a69a" />;
                  }}
                />
                {/* -DI 라인 */}
                <Line 
                  type="monotone" 
                  dataKey="minusDI" 
                  stroke="#ef5350" 
                  strokeWidth={1.5}
                  dot={(props: any) => {
                    const { cx, cy, payload } = props;
                    if (payload?.isCenter) {
                      return <circle cx={cx} cy={cy} r={5} fill="#ef5350" stroke="#fff" strokeWidth={1.5} />;
                    }
                    return <circle cx={cx} cy={cy} r={2} fill="#ef5350" />;
                  }}
                />
              </ComposedChart>
            </ResponsiveContainer>
          </Box>
        );

      case 'cci':
        return (
          <Box sx={{ height: chartHeight }}>
            <ResponsiveContainer width="100%" height="100%">
              <ComposedChart {...commonProps}>
                <CartesianGrid strokeDasharray="3 3" stroke={isDark ? '#2d3748' : '#e0e0e0'} />
                <XAxis dataKey="displayDate" tick={{ fontSize: 11, fill: isDark ? '#a0aec0' : '#666' }} />
                <YAxis 
                  domain={['auto', 'auto']} 
                  hide={true}
                  width={0}
                />
                <Tooltip
                  contentStyle={{
                    backgroundColor: isDark ? '#1a1a2e' : '#fff',
                    border: `1px solid ${isDark ? '#333' : '#ddd'}`,
                    borderRadius: 6,
                    fontSize: 12,
                  }}
                  formatter={(value: any, name: string) => [value?.toFixed(2), name === 'cciSignal' ? 'Signal' : 'CCI']}
                />
                <ReferenceLine y={100} stroke="#ef4444" strokeDasharray="3 3" strokeWidth={1.5} />
                <ReferenceLine y={-100} stroke="#22c55e" strokeDasharray="3 3" strokeWidth={1.5} />
                <ReferenceLine y={0} stroke="#666" strokeDasharray="2 2" strokeWidth={1} />
                <Area type="monotone" dataKey="cci" fill="rgba(0, 188, 212, 0.15)" stroke="none" />
                <Line 
                  type="monotone" 
                  dataKey="cci" 
                  stroke={colors.cciColor || '#00BCD4'} 
                  strokeWidth={colors.cciWidth || 2.5}
                  dot={(props: any) => {
                    const { cx, cy, payload } = props;
                    if (payload?.isCenter) {
                      return <circle cx={cx} cy={cy} r={6} fill={colors.cciColor || '#00BCD4'} stroke="#fff" strokeWidth={2} />;
                    }
                    return <circle cx={cx} cy={cy} r={3} fill={colors.cciColor || '#00BCD4'} />;
                  }}
                />
                {/* CCI Signal 라인 */}
                {indicatorSettings.cciSignalEnabled && (
                  <Line 
                    type="monotone" 
                    dataKey="cciSignal" 
                    stroke={colors.cciSignalColor || '#FF7043'} 
                    strokeWidth={colors.cciSignalWidth || 1}
                    strokeDasharray="3 3"
                    dot={false}
                  />
                )}
              </ComposedChart>
            </ResponsiveContainer>
          </Box>
        );

      case 'trix':
        return (
          <Box sx={{ height: chartHeight }}>
            <ResponsiveContainer width="100%" height="100%">
              <ComposedChart {...commonProps}>
                <CartesianGrid strokeDasharray="3 3" stroke={isDark ? '#2d3748' : '#e0e0e0'} />
                <XAxis dataKey="displayDate" tick={{ fontSize: 11, fill: isDark ? '#a0aec0' : '#666' }} />
                <YAxis 
                  domain={['auto', 'auto']} 
                  hide={true}
                  width={0}
                />
                <Tooltip
                  contentStyle={{
                    backgroundColor: isDark ? '#1a1a2e' : '#fff',
                    border: `1px solid ${isDark ? '#333' : '#ddd'}`,
                    borderRadius: 6,
                    fontSize: 12,
                  }}
                  formatter={(value: any, name: string) => {
                    if (name === 'trix') return [value?.toFixed(4), 'TRIX'];
                    if (name === 'trixSignal') return [value?.toFixed(4), 'Signal'];
                    return [value?.toFixed(4), name];
                  }}
                />
                <ReferenceLine y={0} stroke="#666" strokeDasharray="2 2" strokeWidth={1} />
                {/* TRIX 라인 */}
                <Line 
                  type="monotone" 
                  dataKey="trix" 
                  stroke="#F50057" 
                  strokeWidth={2.5}
                  dot={(props: any) => {
                    const { cx, cy, payload } = props;
                    if (payload?.isCenter) {
                      return <circle cx={cx} cy={cy} r={6} fill="#F50057" stroke="#fff" strokeWidth={2} />;
                    }
                    return <circle cx={cx} cy={cy} r={3} fill="#F50057" />;
                  }}
                />
                {/* Signal 라인 */}
                <Line 
                  type="monotone" 
                  dataKey="trixSignal" 
                  stroke="#18FFFF" 
                  strokeWidth={2}
                  strokeDasharray="5 3"
                  dot={(props: any) => {
                    const { cx, cy, payload } = props;
                    if (payload?.isCenter) {
                      return <circle cx={cx} cy={cy} r={5} fill="#18FFFF" stroke="#fff" strokeWidth={1.5} />;
                    }
                    return <circle cx={cx} cy={cy} r={2} fill="#18FFFF" />;
                  }}
                />
              </ComposedChart>
            </ResponsiveContainer>
          </Box>
        );

      case 'volume':
        return (
          <Box sx={{ height: chartHeight }}>
            <ResponsiveContainer width="100%" height="100%">
              <ComposedChart {...commonProps}>
                <CartesianGrid strokeDasharray="3 3" stroke={isDark ? '#2d3748' : '#e0e0e0'} />
                <XAxis dataKey="displayDate" tick={{ fontSize: 11, fill: isDark ? '#a0aec0' : '#666' }} />
                <YAxis 
                  hide={true}
                  width={0}
                />
                <Tooltip
                  contentStyle={{
                    backgroundColor: isDark ? '#1a1a2e' : '#fff',
                    border: `1px solid ${isDark ? '#333' : '#ddd'}`,
                    borderRadius: 6,
                    fontSize: 12,
                  }}
                  formatter={(value: any) => [value?.toLocaleString(), '거래량']}
                />
                <Bar dataKey="volume">
                  {detailDataWithSignals.map((entry, index) => {
                    const isUp = (entry.close || 0) >= (entry.open || 0);
                    return (
                      <Cell 
                        key={`cell-${index}`} 
                        fill={isUp ? colors.candleRising : colors.candleFalling}
                        opacity={entry.isCenter ? 1 : 0.6}
                      />
                    );
                  })}
                </Bar>
              </ComposedChart>
            </ResponsiveContainer>
          </Box>
        );

      case 'disparity':
        return (
          <Box sx={{ height: chartHeight }}>
            <ResponsiveContainer width="100%" height="100%">
              <ComposedChart {...commonProps}>
                <CartesianGrid strokeDasharray="3 3" stroke={isDark ? '#2d3748' : '#e0e0e0'} />
                <XAxis dataKey="displayDate" tick={{ fontSize: 11, fill: isDark ? '#a0aec0' : '#666' }} />
                <YAxis 
                  domain={[80, 120]} 
                  hide={true}
                  width={0}
                />
                <Tooltip
                  contentStyle={{
                    backgroundColor: isDark ? '#1a1a2e' : '#fff',
                    border: `1px solid ${isDark ? '#333' : '#ddd'}`,
                    borderRadius: 6,
                    fontSize: 12,
                  }}
                  formatter={(value: any) => [`${value?.toFixed(2)}%`, '이격도']}
                />
                {/* 기준선 100% */}
                <ReferenceLine y={100} stroke="#888" strokeDasharray="4 4" strokeWidth={1.5} />
                {/* 과매수/과매도 기준선 */}
                <ReferenceLine y={120} stroke="#f44336" strokeDasharray="2 2" strokeWidth={1} strokeOpacity={0.6} />
                <ReferenceLine y={80} stroke="#4caf50" strokeDasharray="2 2" strokeWidth={1} strokeOpacity={0.6} />
                {/* 이격도 라인 */}
                <Line 
                  type="monotone" 
                  dataKey="disparity" 
                  stroke="#FF9800" 
                  strokeWidth={2.5}
                  dot={(props: any) => {
                    const { cx, cy, payload } = props;
                    if (payload?.isCenter) {
                      return <circle cx={cx} cy={cy} r={6} fill="#FF9800" stroke="#fff" strokeWidth={2} />;
                    }
                    return <circle cx={cx} cy={cy} r={3} fill="#FF9800" />;
                  }}
                />
              </ComposedChart>
            </ResponsiveContainer>
          </Box>
        );

      case 'newPsychological':
        return (
          <Box sx={{ height: chartHeight }}>
            <ResponsiveContainer width="100%" height="100%">
              <ComposedChart {...commonProps}>
                <CartesianGrid strokeDasharray="3 3" stroke={isDark ? '#2d3748' : '#e0e0e0'} />
                <XAxis dataKey="displayDate" tick={{ fontSize: 11, fill: isDark ? '#a0aec0' : '#666' }} />
                <YAxis domain={[0, 100]} hide={true} width={0} />
                <Tooltip contentStyle={{ backgroundColor: isDark ? '#1a1a2e' : '#fff', border: `1px solid ${isDark ? '#333' : '#ddd'}`, borderRadius: 6, fontSize: 12 }} formatter={(value: any) => [value?.toFixed(2), '신심리도']} />
                <ReferenceLine y={75} stroke="#ef4444" strokeDasharray="3 3" strokeWidth={1} />
                <ReferenceLine y={50} stroke="#888" strokeDasharray="2 2" strokeWidth={1} />
                <ReferenceLine y={25} stroke="#22c55e" strokeDasharray="3 3" strokeWidth={1} />
                <Area type="monotone" dataKey="newPsychological" fill="rgba(156, 39, 176, 0.15)" stroke="none" />
                <Line type="monotone" dataKey="newPsychological" stroke="#9C27B0" strokeWidth={2.5} dot={(props: any) => { const { cx, cy, payload } = props; if (payload?.isCenter) { return <circle cx={cx} cy={cy} r={6} fill="#9C27B0" stroke="#fff" strokeWidth={2} />; } return <circle cx={cx} cy={cy} r={3} fill="#9C27B0" />; }} />
              </ComposedChart>
            </ResponsiveContainer>
          </Box>
        );

      case 'investPsychological':
        return (
          <Box sx={{ height: chartHeight }}>
            <ResponsiveContainer width="100%" height="100%">
              <ComposedChart {...commonProps}>
                <CartesianGrid strokeDasharray="3 3" stroke={isDark ? '#2d3748' : '#e0e0e0'} />
                <XAxis dataKey="displayDate" tick={{ fontSize: 11, fill: isDark ? '#a0aec0' : '#666' }} />
                <YAxis domain={[0, 100]} hide={true} width={0} />
                <Tooltip contentStyle={{ backgroundColor: isDark ? '#1a1a2e' : '#fff', border: `1px solid ${isDark ? '#333' : '#ddd'}`, borderRadius: 6, fontSize: 12 }} formatter={(value: any) => [value?.toFixed(2), '투자심리도']} />
                <ReferenceLine y={75} stroke="#ef4444" strokeDasharray="3 3" strokeWidth={1} />
                <ReferenceLine y={50} stroke="#888" strokeDasharray="2 2" strokeWidth={1} />
                <ReferenceLine y={25} stroke="#22c55e" strokeDasharray="3 3" strokeWidth={1} />
                <Area type="monotone" dataKey="investPsychological" fill="rgba(233, 30, 99, 0.15)" stroke="none" />
                <Line type="monotone" dataKey="investPsychological" stroke="#E91E63" strokeWidth={2.5} dot={(props: any) => { const { cx, cy, payload } = props; if (payload?.isCenter) { return <circle cx={cx} cy={cy} r={6} fill="#E91E63" stroke="#fff" strokeWidth={2} />; } return <circle cx={cx} cy={cy} r={3} fill="#E91E63" />; }} />
              </ComposedChart>
            </ResponsiveContainer>
          </Box>
        );

      case 'bwi':
        return (
          <Box sx={{ height: chartHeight }}>
            <ResponsiveContainer width="100%" height="100%">
              <ComposedChart {...commonProps}>
                <CartesianGrid strokeDasharray="3 3" stroke={isDark ? '#2d3748' : '#e0e0e0'} />
                <XAxis dataKey="displayDate" tick={{ fontSize: 11, fill: isDark ? '#a0aec0' : '#666' }} />
                <YAxis domain={['auto', 'auto']} hide={true} width={0} />
                <Tooltip contentStyle={{ backgroundColor: isDark ? '#1a1a2e' : '#fff', border: `1px solid ${isDark ? '#333' : '#ddd'}`, borderRadius: 6, fontSize: 12 }} formatter={(value: any) => [value?.toFixed(2), 'BWI']} />
                <Area type="monotone" dataKey="bwi" fill="rgba(255, 152, 0, 0.15)" stroke="none" />
                <Line type="monotone" dataKey="bwi" stroke="#FF9800" strokeWidth={2.5} dot={(props: any) => { const { cx, cy, payload } = props; if (payload?.isCenter) { return <circle cx={cx} cy={cy} r={6} fill="#FF9800" stroke="#fff" strokeWidth={2} />; } return <circle cx={cx} cy={cy} r={3} fill="#FF9800" />; }} />
              </ComposedChart>
            </ResponsiveContainer>
          </Box>
        );

      case 'dmi':
        return (
          <Box sx={{ height: chartHeight }}>
            <ResponsiveContainer width="100%" height="100%">
              <ComposedChart {...commonProps}>
                <CartesianGrid strokeDasharray="3 3" stroke={isDark ? '#2d3748' : '#e0e0e0'} />
                <XAxis dataKey="displayDate" tick={{ fontSize: 11, fill: isDark ? '#a0aec0' : '#666' }} />
                <YAxis domain={[0, 'auto']} hide={true} width={0} />
                <Tooltip contentStyle={{ backgroundColor: isDark ? '#1a1a2e' : '#fff', border: `1px solid ${isDark ? '#333' : '#ddd'}`, borderRadius: 6, fontSize: 12 }} formatter={(value: any, name: string) => [value?.toFixed(2), name === 'plusDI' ? '+DI' : '-DI']} />
                <Line type="monotone" dataKey="plusDI" stroke="#26a69a" strokeWidth={2} dot={(props: any) => { const { cx, cy, payload } = props; if (payload?.isCenter) { return <circle cx={cx} cy={cy} r={5} fill="#26a69a" stroke="#fff" strokeWidth={2} />; } return <circle cx={cx} cy={cy} r={2} fill="#26a69a" />; }} />
                <Line type="monotone" dataKey="minusDI" stroke="#ef5350" strokeWidth={2} dot={(props: any) => { const { cx, cy, payload } = props; if (payload?.isCenter) { return <circle cx={cx} cy={cy} r={5} fill="#ef5350" stroke="#fff" strokeWidth={2} />; } return <circle cx={cx} cy={cy} r={2} fill="#ef5350" />; }} />
              </ComposedChart>
            </ResponsiveContainer>
          </Box>
        );

      case 'obv':
        return (
          <Box sx={{ height: chartHeight }}>
            <ResponsiveContainer width="100%" height="100%">
              <ComposedChart {...commonProps}>
                <CartesianGrid strokeDasharray="3 3" stroke={isDark ? '#2d3748' : '#e0e0e0'} />
                <XAxis dataKey="displayDate" tick={{ fontSize: 11, fill: isDark ? '#a0aec0' : '#666' }} />
                <YAxis domain={['auto', 'auto']} hide={true} width={0} />
                <Tooltip contentStyle={{ backgroundColor: isDark ? '#1a1a2e' : '#fff', border: `1px solid ${isDark ? '#333' : '#ddd'}`, borderRadius: 6, fontSize: 12 }} formatter={(value: any, name: string) => [value?.toLocaleString(), name === 'obvSignal' ? 'Signal' : 'OBV']} />
                <Area type="monotone" dataKey="obv" fill="rgba(0, 188, 212, 0.15)" stroke="none" />
                <Line type="monotone" dataKey="obv" stroke={colors.obvColor || '#00BCD4'} strokeWidth={colors.obvWidth || 2.5} dot={(props: any) => { const { cx, cy, payload } = props; if (payload?.isCenter) { return <circle cx={cx} cy={cy} r={6} fill={colors.obvColor || '#00BCD4'} stroke="#fff" strokeWidth={2} />; } return <circle cx={cx} cy={cy} r={3} fill={colors.obvColor || '#00BCD4'} />; }} />
                {/* OBV Signal 라인 */}
                <Line type="monotone" dataKey="obvSignal" stroke={colors.obvSignalColor || '#FF7043'} strokeWidth={colors.obvSignalWidth || 1} strokeDasharray="3 3" dot={false} />
              </ComposedChart>
            </ResponsiveContainer>
          </Box>
        );

      case 'williamsR':
        return (
          <Box sx={{ height: chartHeight }}>
            <ResponsiveContainer width="100%" height="100%">
              <ComposedChart {...commonProps}>
                <CartesianGrid strokeDasharray="3 3" stroke={isDark ? '#2d3748' : '#e0e0e0'} />
                <XAxis dataKey="displayDate" tick={{ fontSize: 11, fill: isDark ? '#a0aec0' : '#666' }} />
                <YAxis domain={[-100, 0]} hide={true} width={0} />
                <Tooltip contentStyle={{ backgroundColor: isDark ? '#1a1a2e' : '#fff', border: `1px solid ${isDark ? '#333' : '#ddd'}`, borderRadius: 6, fontSize: 12 }} formatter={(value: any) => [value?.toFixed(2), 'Williams %R']} />
                <ReferenceLine y={-20} stroke="#ef4444" strokeDasharray="3 3" strokeWidth={1} />
                <ReferenceLine y={-50} stroke="#888" strokeDasharray="2 2" strokeWidth={1} />
                <ReferenceLine y={-80} stroke="#22c55e" strokeDasharray="3 3" strokeWidth={1} />
                <Area type="monotone" dataKey="williamsR" fill="rgba(255, 87, 34, 0.15)" stroke="none" />
                <Line type="monotone" dataKey="williamsR" stroke="#FF5722" strokeWidth={2.5} dot={(props: any) => { const { cx, cy, payload } = props; if (payload?.isCenter) { return <circle cx={cx} cy={cy} r={6} fill="#FF5722" stroke="#fff" strokeWidth={2} />; } return <circle cx={cx} cy={cy} r={3} fill="#FF5722" />; }} />
              </ComposedChart>
            </ResponsiveContainer>
          </Box>
        );

      case 'volumeOsc':
        return (
          <Box sx={{ height: chartHeight }}>
            <ResponsiveContainer width="100%" height="100%">
              <ComposedChart {...commonProps}>
                <CartesianGrid strokeDasharray="3 3" stroke={isDark ? '#2d3748' : '#e0e0e0'} />
                <XAxis dataKey="displayDate" tick={{ fontSize: 11, fill: isDark ? '#a0aec0' : '#666' }} />
                <YAxis domain={['auto', 'auto']} hide={true} width={0} />
                <Tooltip contentStyle={{ backgroundColor: isDark ? '#1a1a2e' : '#fff', border: `1px solid ${isDark ? '#333' : '#ddd'}`, borderRadius: 6, fontSize: 12 }} formatter={(value: any) => [`${value?.toFixed(2)}%`, 'VolumeOSC']} />
                <ReferenceLine y={0} stroke="#888" strokeDasharray="2 2" strokeWidth={1} />
                <Bar dataKey="volumeOsc">
                  {detailDataWithSignals.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={(entry.volumeOsc || 0) >= 0 ? '#4CAF50' : '#f44336'} opacity={entry.isCenter ? 1 : 0.6} />
                  ))}
                </Bar>
              </ComposedChart>
            </ResponsiveContainer>
          </Box>
        );

      case 'vr':
        return (
          <Box sx={{ height: chartHeight }}>
            <ResponsiveContainer width="100%" height="100%">
              <ComposedChart {...commonProps}>
                <CartesianGrid strokeDasharray="3 3" stroke={isDark ? '#2d3748' : '#e0e0e0'} />
                <XAxis dataKey="displayDate" tick={{ fontSize: 11, fill: isDark ? '#a0aec0' : '#666' }} />
                <YAxis domain={[0, 'auto']} hide={true} width={0} />
                <Tooltip contentStyle={{ backgroundColor: isDark ? '#1a1a2e' : '#fff', border: `1px solid ${isDark ? '#333' : '#ddd'}`, borderRadius: 6, fontSize: 12 }} formatter={(value: any) => [value?.toFixed(2), 'VR']} />
                <ReferenceLine y={70} stroke="#22c55e" strokeDasharray="3 3" strokeWidth={1} />
                <ReferenceLine y={100} stroke="#888" strokeDasharray="2 2" strokeWidth={1} />
                <ReferenceLine y={250} stroke="#ef4444" strokeDasharray="3 3" strokeWidth={1} />
                <Area type="monotone" dataKey="vr" fill="rgba(255, 193, 7, 0.15)" stroke="none" />
                <Line type="monotone" dataKey="vr" stroke="#FFC107" strokeWidth={2.5} dot={(props: any) => { const { cx, cy, payload } = props; if (payload?.isCenter) { return <circle cx={cx} cy={cy} r={6} fill="#FFC107" stroke="#fff" strokeWidth={2} />; } return <circle cx={cx} cy={cy} r={3} fill="#FFC107" />; }} />
              </ComposedChart>
            </ResponsiveContainer>
          </Box>
        );

      default:
        return (
          <Box sx={{ height: chartHeight, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Typography color="text.secondary" sx={{ fontSize: 13 }}>해당 차트는 준비 중입니다.</Typography>
          </Box>
        );
    }
  };

  if (!open) return null;

  return (
    <Paper
      ref={popupRef}
      elevation={8}
      sx={{
        position: 'fixed',
        left: position.x,
        top: position.y,
        width: isMinimized ? MINIMIZED_SIZE : POPUP_SIZE,
        height: isMinimized ? 'auto' : POPUP_SIZE,
        zIndex: 1300,
        borderRadius: 2,
        bgcolor: isDark ? `rgba(26, 26, 46, ${opacity / 100})` : `rgba(255, 255, 255, ${opacity / 100})`,
        backdropFilter: opacity > 50 ? 'blur(10px)' : 'blur(5px)',
        border: `1px solid ${isDark ? '#444' : '#ccc'}`,
        overflow: 'hidden',
        transition: 'width 0.2s, height 0.2s, background-color 0.2s',
        pointerEvents: 'auto',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      {/* 헤더 (드래그 영역) */}
      <Box
        onMouseDown={handleMouseDown}
        sx={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          px: 1.5,
          py: 1,
          bgcolor: isDark ? `rgba(39, 39, 58, ${Math.min(opacity / 100 + 0.1, 1)})` : `rgba(245, 245, 245, ${Math.min(opacity / 100 + 0.1, 1)})`,
          borderBottom: `1px solid ${isDark ? '#444' : '#ddd'}`,
          cursor: isDragging ? 'grabbing' : 'grab',
          userSelect: 'none',
          flexShrink: 0,
        }}
      >
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <DragIndicator sx={{ fontSize: 18, color: isDark ? '#666' : '#999', cursor: 'grab' }} />
          <Typography sx={{ fontSize: 14, fontWeight: 600 }}>
            {getChartIcon()} {getChartTitle()}
          </Typography>
          {signal && (
            <Chip
              label={signal === 'BUY' ? '매수' : '매도'}
              size="small"
              sx={{
                height: 20,
                fontSize: 11,
                bgcolor: signal === 'BUY' ? 'rgba(34, 197, 94, 0.2)' : 'rgba(239, 68, 68, 0.2)',
                color: signal === 'BUY' ? '#22c55e' : '#ef4444',
              }}
            />
          )}
        </Box>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
          <IconButton 
            size="small" 
            onClick={() => setIsMinimized(!isMinimized)}
            sx={{ p: 0.5 }}
          >
            {isMinimized ? <OpenInFull sx={{ fontSize: 16 }} /> : <Minimize sx={{ fontSize: 16 }} />}
          </IconButton>
          <IconButton size="small" onClick={onClose} sx={{ p: 0.5 }}>
            <Close sx={{ fontSize: 18 }} />
          </IconButton>
        </Box>
      </Box>
      
      {/* 투명도 조절 슬라이더 */}
      {!isMinimized && (
        <Box sx={{ 
          px: 2, 
          py: 1, 
          bgcolor: isDark ? `rgba(30, 35, 50, ${Math.min(opacity / 100 + 0.1, 1)})` : `rgba(249, 249, 249, ${Math.min(opacity / 100 + 0.1, 1)})`,
          borderBottom: `1px solid ${isDark ? '#333' : '#eee'}`,
          flexShrink: 0,
        }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
            <Typography sx={{ fontSize: 11, color: isDark ? '#888' : '#666', minWidth: 60 }}>
              투명도: {opacity}%
            </Typography>
            <Slider
              value={opacity}
              onChange={(_, value) => setOpacity(value as number)}
              min={0}
              max={100}
              size="small"
              sx={{
                flex: 1,
                '& .MuiSlider-thumb': {
                  width: 12,
                  height: 12,
                },
                '& .MuiSlider-track': {
                  height: 3,
                },
              }}
            />
          </Box>
        </Box>
      )}

      {/* 데이터 정보 */}
      {!isMinimized && centerData && (
        <Box sx={{ 
          px: 1.5, 
          py: 1,
          bgcolor: isDark ? `rgba(30, 35, 50, ${Math.min(opacity / 100 * 0.6, 0.6)})` : `rgba(249, 249, 249, ${Math.min(opacity / 100, 1)})`,
          borderBottom: `1px solid ${isDark ? '#333' : '#eee'}`,
          display: 'flex',
          gap: 2,
          flexWrap: 'wrap',
          alignItems: 'center',
          flexShrink: 0,
        }}>
          {chartType === 'candle' && (
            <>
              <Box sx={{ textAlign: 'center' }}>
                <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>시가</Typography>
                <Typography sx={{ fontSize: 12, fontWeight: 600 }}>{centerData.open?.toLocaleString()}</Typography>
              </Box>
              <Box sx={{ textAlign: 'center' }}>
                <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>고가</Typography>
                <Typography sx={{ fontSize: 12, fontWeight: 600, color: '#22c55e' }}>{centerData.high?.toLocaleString()}</Typography>
              </Box>
              <Box sx={{ textAlign: 'center' }}>
                <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>저가</Typography>
                <Typography sx={{ fontSize: 12, fontWeight: 600, color: '#ef4444' }}>{centerData.low?.toLocaleString()}</Typography>
              </Box>
              <Box sx={{ textAlign: 'center' }}>
                <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>종가</Typography>
                <Typography sx={{ fontSize: 12, fontWeight: 600 }}>{centerData.close?.toLocaleString()}</Typography>
              </Box>
            </>
          )}
          {chartType === 'macd' && (
            <>
              <Box sx={{ textAlign: 'center' }}>
                <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>MACD</Typography>
                <Typography sx={{ fontSize: 12, fontWeight: 600, color: colors.macdLine }}>{centerData.macdLine?.toFixed(2)}</Typography>
              </Box>
              <Box sx={{ textAlign: 'center' }}>
                <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>Signal</Typography>
                <Typography sx={{ fontSize: 12, fontWeight: 600, color: colors.signalLine }}>{centerData.signalLine?.toFixed(2)}</Typography>
              </Box>
              <Box sx={{ textAlign: 'center' }}>
                <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>Hist</Typography>
                <Typography sx={{ 
                  fontSize: 12, 
                  fontWeight: 600, 
                  color: (centerData.macdHistogram || 0) >= 0 ? '#22c55e' : '#ef4444' 
                }}>
                  {centerData.macdHistogram?.toFixed(2)}
                </Typography>
              </Box>
            </>
          )}
          {chartType === 'stochastic' && (
            <>
              <Box sx={{ textAlign: 'center' }}>
                <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>%K</Typography>
                <Typography sx={{ fontSize: 12, fontWeight: 600, color: colors.stochasticK }}>{centerData.stochasticK?.toFixed(2)}</Typography>
              </Box>
              <Box sx={{ textAlign: 'center' }}>
                <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>%D</Typography>
                <Typography sx={{ fontSize: 12, fontWeight: 600, color: colors.stochasticD }}>{centerData.stochasticD?.toFixed(2)}</Typography>
              </Box>
            </>
          )}
          {chartType === 'rsi' && (
            <Box sx={{ textAlign: 'center' }}>
              <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>RSI</Typography>
              <Typography sx={{ fontSize: 12, fontWeight: 600, color: '#8b5cf6' }}>{centerData.rsi?.toFixed(2)}</Typography>
            </Box>
          )}
          {chartType === 'adx' && (
            <>
              <Box sx={{ textAlign: 'center' }}>
                <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>ADX</Typography>
                <Typography sx={{ fontSize: 12, fontWeight: 600, color: '#FFD54F' }}>{centerData.adx?.toFixed(2)}</Typography>
              </Box>
              <Box sx={{ textAlign: 'center' }}>
                <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>+DI</Typography>
                <Typography sx={{ fontSize: 12, fontWeight: 600, color: '#26a69a' }}>{centerData.plusDI?.toFixed(2)}</Typography>
              </Box>
              <Box sx={{ textAlign: 'center' }}>
                <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>-DI</Typography>
                <Typography sx={{ fontSize: 12, fontWeight: 600, color: '#ef5350' }}>{centerData.minusDI?.toFixed(2)}</Typography>
              </Box>
            </>
          )}
          {chartType === 'cci' && (
            <Box sx={{ textAlign: 'center' }}>
              <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>CCI</Typography>
              <Typography sx={{ fontSize: 12, fontWeight: 600, color: '#00BCD4' }}>{centerData.cci?.toFixed(2)}</Typography>
            </Box>
          )}
          {chartType === 'trix' && (
            <>
              <Box sx={{ textAlign: 'center' }}>
                <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>TRIX</Typography>
                <Typography sx={{ fontSize: 12, fontWeight: 600, color: '#F50057' }}>{centerData.trix?.toFixed(4)}</Typography>
              </Box>
              <Box sx={{ textAlign: 'center' }}>
                <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>Signal</Typography>
                <Typography sx={{ fontSize: 12, fontWeight: 600, color: '#18FFFF' }}>{centerData.trixSignal?.toFixed(4)}</Typography>
              </Box>
            </>
          )}
          {chartType === 'volume' && centerData.volume && (
            <Box sx={{ textAlign: 'center' }}>
              <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>거래량</Typography>
              <Typography sx={{ fontSize: 12, fontWeight: 600 }}>{centerData.volume?.toLocaleString()}</Typography>
            </Box>
          )}
          {chartType === 'disparity' && (
            <Box sx={{ textAlign: 'center' }}>
              <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>이격도</Typography>
              <Typography sx={{ fontSize: 12, fontWeight: 600, color: '#FF9800' }}>{centerData.disparity?.toFixed(2)}%</Typography>
            </Box>
          )}
          {chartType === 'newPsychological' && (
            <Box sx={{ textAlign: 'center' }}>
              <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>신심리도</Typography>
              <Typography sx={{ fontSize: 12, fontWeight: 600, color: '#9C27B0' }}>{centerData.newPsychological?.toFixed(2)}</Typography>
            </Box>
          )}
          {chartType === 'investPsychological' && (
            <Box sx={{ textAlign: 'center' }}>
              <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>투자심리도</Typography>
              <Typography sx={{ fontSize: 12, fontWeight: 600, color: '#E91E63' }}>{centerData.investPsychological?.toFixed(2)}</Typography>
            </Box>
          )}
          {chartType === 'bwi' && (
            <Box sx={{ textAlign: 'center' }}>
              <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>BWI</Typography>
              <Typography sx={{ fontSize: 12, fontWeight: 600, color: '#FF9800' }}>{centerData.bwi?.toFixed(2)}</Typography>
            </Box>
          )}
          {chartType === 'dmi' && (
            <>
              <Box sx={{ textAlign: 'center' }}>
                <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>+DI</Typography>
                <Typography sx={{ fontSize: 12, fontWeight: 600, color: '#26a69a' }}>{centerData.plusDI?.toFixed(2)}</Typography>
              </Box>
              <Box sx={{ textAlign: 'center' }}>
                <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>-DI</Typography>
                <Typography sx={{ fontSize: 12, fontWeight: 600, color: '#ef5350' }}>{centerData.minusDI?.toFixed(2)}</Typography>
              </Box>
            </>
          )}
          {chartType === 'obv' && (
            <Box sx={{ textAlign: 'center' }}>
              <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>OBV</Typography>
              <Typography sx={{ fontSize: 12, fontWeight: 600, color: '#00BCD4' }}>{centerData.obv?.toLocaleString()}</Typography>
            </Box>
          )}
          {chartType === 'williamsR' && (
            <Box sx={{ textAlign: 'center' }}>
              <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>Williams %R</Typography>
              <Typography sx={{ fontSize: 12, fontWeight: 600, color: '#FF5722' }}>{centerData.williamsR?.toFixed(2)}</Typography>
            </Box>
          )}
          {chartType === 'volumeOsc' && (
            <Box sx={{ textAlign: 'center' }}>
              <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>VolumeOSC</Typography>
              <Typography sx={{ fontSize: 12, fontWeight: 600, color: (centerData.volumeOsc || 0) >= 0 ? '#4CAF50' : '#f44336' }}>{centerData.volumeOsc?.toFixed(2)}%</Typography>
            </Box>
          )}
          {chartType === 'vr' && (
            <Box sx={{ textAlign: 'center' }}>
              <Typography sx={{ fontSize: 10, color: isDark ? '#71717a' : '#999' }}>VR</Typography>
              <Typography sx={{ fontSize: 12, fontWeight: 600, color: '#FFC107' }}>{centerData.vr?.toFixed(2)}</Typography>
            </Box>
          )}
        </Box>
      )}

      {/* 차트 영역 */}
      <Box 
        ref={chartAreaRef}
        sx={{ 
          p: 1.5, 
          flex: 1,
          display: 'flex',
          flexDirection: 'column',
          cursor: 'ns-resize',
        }}
      >
        {renderChart()}
      </Box>

      {/* 줌 컨트롤 바 */}
      {!isMinimized && (
        <Box sx={{ 
          px: 2, 
          py: 1,
          bgcolor: isDark ? 'rgba(30, 35, 50, 0.6)' : '#f5f5f5',
          borderTop: `1px solid ${isDark ? '#333' : '#eee'}`,
          display: 'flex',
          alignItems: 'center',
          gap: 1.5,
          flexShrink: 0,
        }}>
          <IconButton size="small" onClick={handleZoomIn} disabled={zoomRange <= MIN_RANGE}>
            <ZoomIn sx={{ fontSize: 18 }} />
          </IconButton>
          <Box sx={{ flex: 1, display: 'flex', alignItems: 'center' }}>
            <Slider
              value={zoomRange}
              min={MIN_RANGE}
              max={MAX_RANGE}
              step={1}
              onChange={(_, value) => setZoomRange(value as number)}
              sx={{
                color: isDark ? '#6366f1' : '#3b82f6',
                '& .MuiSlider-thumb': {
                  width: 14,
                  height: 14,
                },
                '& .MuiSlider-track': {
                  height: 4,
                },
                '& .MuiSlider-rail': {
                  height: 4,
                  opacity: 0.3,
                },
              }}
            />
          </Box>
          <IconButton size="small" onClick={handleZoomOut} disabled={zoomRange >= MAX_RANGE}>
            <ZoomOut sx={{ fontSize: 18 }} />
          </IconButton>
          <Typography sx={{ fontSize: 11, color: isDark ? '#71717a' : '#999', minWidth: 60 }}>
            ±{zoomRange} 캔들
          </Typography>
        </Box>
      )}
    </Paper>
  );
};

export default ChartDetailPopup;
