import React, { useState, useEffect, useRef, useCallback } from 'react';
import {
  Box,
  Paper,
  Typography,
  Grid,
  TextField,
  Button,
  Card,
  CardContent,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  CircularProgress,
  Alert,
  Chip,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Divider,
  Tooltip,
  IconButton,
} from '@mui/material';
import {
  PlayArrow,
  Assessment,
  TrendingUp,
  TrendingDown,
  ShowChart,
  Info,
  Refresh,
} from '@mui/icons-material';
import { Line } from 'react-chartjs-2';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip as ChartTooltip,
  Legend,
  Filler,
} from 'chart.js';
import type { Time } from 'lightweight-charts';
import { runBacktest, BacktestResult, BacktestRequest, TradeRecord, CandleData, IndicatorData } from '../services/backtestApi';
import { getStrategies, TradingStrategy } from '../services/tradingStrategyApi';
import { useIndicatorVisibility } from '../contexts/IndicatorVisibilityContext';
import { upbitApiService, CryptoInfo } from '../services/upbitApi';
import MacdChart from '../components/MacdChart';
import CryptoListPanel from '../components/CryptoListPanel';
import { MacdResult } from '../types/stock';
import { useChartColors } from '../contexts/ChartColorContext';
import { loadIndicatorSettings } from '../components/settings/IndicatorSettingsTab';

// Chart.js 등록
ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  ChartTooltip,
  Legend,
  Filler
);

/**
 * 전략 백테스팅 탭 컴포넌트
 */
const StrategyPage: React.FC = () => {
  const [strategies, setStrategies] = useState<TradingStrategy[]>([]);
  const [cryptoList, setCryptoList] = useState<CryptoInfo[]>([]);
  const [selectedStrategy, setSelectedStrategy] = useState<number | ''>('');
  const [symbol, setSymbol] = useState<string>('KRW-BTC');
  const [timeframe, setTimeframe] = useState<string>('1d');
  const [period, setPeriod] = useState<string>('1month');
  const [initialCapital, setInitialCapital] = useState<number>(10000000);
  const [loading, setLoading] = useState<boolean>(false);
  const [result, setResult] = useState<BacktestResult | null>(null);
  const [error, setError] = useState<string>('');
  
  // 차트 색상 설정 가져오기
  const { colors } = useChartColors();
  const { settings: indicatorSettings } = useIndicatorVisibility();
  const [chartTimeRange, setChartTimeRange] = useState<{ from: number; to: number } | undefined>(undefined);
  
  // 차트 네비게이션 상태 (커서 기반)
  const [cursor, setCursor] = useState<number>(0); // 0 = 현재 시점, 음수 = 과거
  
  // 전체화면 모드 상태
  const [isChartFullscreen, setIsChartFullscreen] = useState<boolean>(false);
  
  // 전체화면 토글 핸들러
  const handleToggleFullscreen = () => {
    setIsChartFullscreen(!isChartFullscreen);
  };
  
  // ESC 키로 전체화면 종료
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && isChartFullscreen) {
        setIsChartFullscreen(false);
      }
    };
    
    if (isChartFullscreen) {
      document.addEventListener('keydown', handleKeyDown);
    }
    
    return () => {
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [isChartFullscreen]);

  // 차트 간 crosshair 동기화를 위한 ref (하위 호환성 유지) - MacdChart는 ref를 지원하지 않음
  // const indicatorChartRef = useRef<any>(null);
  // const macdChartRef = useRef<any>(null);

  // 지표 차트 crosshair 동기화 (하위 호환성)
  const handleIndicatorCrosshairMove = useCallback((time: Time | null) => {
    // MacdChart는 자체적으로 crosshair 처리
  }, []);

  const handleMacdCrosshairMove = useCallback((time: Time | null) => {
    // MacdChart는 자체적으로 crosshair 처리
  }, []);

  const handleIndicatorVisibleRangeChange = useCallback((from: number, to: number) => {
    // MacdChart는 자체적으로 시간축 처리
  }, []);

  const handleMacdVisibleRangeChange = useCallback((from: number, to: number) => {
    // MacdChart는 자체적으로 시간축 처리
  }, []);

  // 전략 목록 및 암호화폐 목록 로드
  useEffect(() => {
    loadStrategies();
    loadCryptos();
  }, []);

  const loadStrategies = async () => {
    try {
      // 활성화된 전략만 가져오기 (activeOnly = true)
      const data = await getStrategies(true);
      setStrategies(data);
      
      // 현재 선택된 전략이 목록에 없으면 첫 번째 전략 선택
      if (data.length > 0) {
        const currentSelected = selectedStrategy;
        const isCurrentInList = data.some(s => s.id === currentSelected);
        if (!isCurrentInList) {
          setSelectedStrategy(data[0].id!);
        }
      } else {
        setSelectedStrategy('');
      }
    } catch (err) {
      console.error('전략 목록 로드 실패:', err);
      setError('전략 목록을 불러올 수 없습니다.');
    }
  };

  const loadCryptos = async () => {
    try {
      const data = await upbitApiService.getActiveCryptos();
      setCryptoList(data);
    } catch (err) {
      console.error('암호화폐 목록 로드 실패:', err);
      setError('암호화폐 목록을 불러올 수 없습니다.');
    }
  };

  /**
   * 기간(일 수) 계산
   */
  const getPeriodDays = (periodValue: string): number => {
    switch (periodValue) {
      case '1day': return 1;
      case '1week': return 7;
      case '10days': return 10;
      case '15days': return 15;
      case '1month': return 30;
      case '3months': return 90;
      case '6months': return 180;
      default: return 30;
    }
  };

  /**
   * BacktestResult 데이터를 MacdResult 형식으로 변환
   * 
   * 시분봉 데이터 지원: timeframe에 따라 적절한 시간 키로 매핑
   * - 일봉/주봉/월봉: 날짜만으로 매핑 (YYYY-MM-DD)
   * - 시분봉: 전체 타임스탬프로 매핑 (정확한 1:1 매칭)
   */
  const convertToMacdResult = (candleData: CandleData[], indicatorData: IndicatorData[]): MacdResult[] => {
    // 데이터가 없으면 빈 배열 반환
    if (!candleData || candleData.length === 0) {
      console.warn('⚠️ convertToMacdResult: candleData가 비어있음');
      return [];
    }
    
    // 시분봉 여부 확인 (timeframe이 분/시간 단위인 경우, 단 월봉 '1M'은 제외)
    const isIntraday = (timeframe.endsWith('m') && timeframe !== '1M') || timeframe.endsWith('h');
    
    console.log(`📊 데이터 변환: timeframe=${timeframe}, isIntraday=${isIntraday}, candleData=${candleData.length}개, indicatorData=${indicatorData.length}개`);
    
    // 지표 데이터를 time 기준 맵으로 변환
    const indicatorMap = new Map<string, IndicatorData>();
    indicatorData.forEach(ind => {
      if (isIntraday) {
        // 시분봉: 전체 타임스탬프를 키로 사용 (여러 형식 지원)
        indicatorMap.set(ind.time, ind);
        // ISO 형식 변환 키도 추가 (T 포함/미포함 모두 지원)
        if (ind.time.includes('T')) {
          indicatorMap.set(ind.time.replace('T', ' '), ind);
        } else if (ind.time.includes(' ')) {
          indicatorMap.set(ind.time.replace(' ', 'T'), ind);
        }
      } else {
        // 일봉/주봉/월봉: 날짜만 키로 사용
        const dateKey = ind.time.split('T')[0];
        indicatorMap.set(dateKey, ind);
      }
    });

    // 인덱스 기반 매핑 준비 (타임스탬프 매핑 실패 시 fallback)
    // candleData와 indicatorData의 순서가 동일하다고 가정
    const useIndexMapping = isIntraday && candleData.length === indicatorData.length;

    return candleData.map((candle, index) => {
      let indicator: IndicatorData | undefined;
      
      if (isIntraday) {
        // 시분봉: 여러 키 형식으로 시도
        indicator = indicatorMap.get(candle.time);
        if (!indicator && candle.time.includes('T')) {
          indicator = indicatorMap.get(candle.time.replace('T', ' '));
        }
        if (!indicator && candle.time.includes(' ')) {
          indicator = indicatorMap.get(candle.time.replace(' ', 'T'));
        }
        // 매핑 실패 시 인덱스 기반 매핑 사용
        if (!indicator && useIndexMapping) {
          indicator = indicatorData[index];
        }
      } else {
        // 일봉/주봉/월봉: 날짜로 매핑
        const dateKey = candle.time.split('T')[0];
        indicator = indicatorMap.get(dateKey);
      }
      
      // 날짜 형식 결정 (표시용) - 시분봉일 경우 시:분까지 표시
      let displayDate = candle.time;
      if (isIntraday) {
        // ISO 형식에서 날짜와 시간 추출 (YYYY-MM-DDTHH:mm:ss → MM/DD HH:mm)
        try {
          const date = new Date(candle.time);
          if (!isNaN(date.getTime())) {
            displayDate = `${String(date.getMonth() + 1).padStart(2, '0')}/${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
          }
        } catch {
          displayDate = candle.time;
        }
      } else {
        displayDate = candle.time.split('T')[0];
      }
      
      return {
        date: displayDate,
        timestamp: candle.time,
        open: candle.open,
        high: candle.high,
        low: candle.low,
        close: candle.close,
        volume: candle.volume,
        macdLine: indicator?.macdLine ?? null,
        signalLine: indicator?.signalLine ?? null,
        macdHistogram: indicator?.histogram ?? null,
        signal: candle.isBuyPoint ? 'BUY' : candle.isSellPoint ? 'SELL' : 'HOLD',
        stochasticK: indicator?.stochK ?? null,
        stochasticD: indicator?.stochD ?? null,
        adx: indicator?.adx ?? null,
        plusDI: indicator?.plusDI ?? null,
        minusDI: indicator?.minusDI ?? null,
        cci13: indicator?.cci ?? null,
        rsi: indicator?.rsi ?? null,
        sma12: null,
        sma26: null,
        sma60: null,
        // 일목균형표 (Ichimoku Cloud)
        ichimokuTenkan: indicator?.ichimokuTenkan ?? null,
        ichimokuKijun: indicator?.ichimokuKijun ?? null,
        ichimokuChikou: indicator?.ichimokuChikou ?? null,
        ichimokuSenkouA: indicator?.ichimokuSenkouA ?? null,
        ichimokuSenkouB: indicator?.ichimokuSenkouB ?? null,
        // TRIX
        trix: indicator?.trix ?? null,
        trixSignal: indicator?.trixSignal ?? null,
      } as MacdResult;
    });
  };

  /**
   * 기간에 따른 날짜 범위 계산 (cursor 고려)
   */
  const calculateDateRange = (periodValue: string, cursorOffset: number = 0): { startDate: string; endDate: string } => {
    const periodDays = getPeriodDays(periodValue);
    
    // 종료일: 현재 날짜에서 cursor * periodDays만큼 이동
    const endDate = new Date();
    endDate.setDate(endDate.getDate() + cursorOffset * periodDays);
    
    // 시작일: 종료일에서 periodDays만큼 이전
    const startDate = new Date(endDate.getTime()); // 밀리초로 복사하여 완전히 새 객체 생성
    startDate.setDate(startDate.getDate() - periodDays);
    
    return {
      startDate: startDate.toISOString().split('T')[0] + 'T00:00:00',
      endDate: endDate.toISOString().split('T')[0] + 'T23:59:59',
    };
  };

  /**
   * 차트 네비게이션 핸들러 (과거/미래 기간 이동)
   */
  const handleChartNavigate = useCallback(async (direction: 'past' | 'future') => {
    if (loading) return;
    
    const newCursor = direction === 'past' ? cursor - 1 : cursor + 1;
    
    // 미래 시점(cursor > 0)으로는 이동 불가
    if (newCursor > 0) return;
    
    // 백테스팅 재실행
    if (!selectedStrategy || !symbol) {
      setError('전략과 종목을 선택해주세요.');
      return;
    }

    // cursor 먼저 업데이트
    setCursor(newCursor);
    setLoading(true);
    setError('');

    try {
      const { startDate, endDate } = calculateDateRange(period, newCursor);
      
      // 보조지표 설정 가져오기
      const indicatorSettings = loadIndicatorSettings();
      
      const request: BacktestRequest = {
        symbol,
        strategyId: Number(selectedStrategy),
        startDate,
        endDate,
        timeframe,
        initialCapital,
        positionSizeRatio: 1.0,
        commissionRate: 0.0005,
        // 보조지표 파라미터 (설정 > 보조지표 설정에서 동기화)
        macdFastPeriod: indicatorSettings.macdFastPeriod,
        macdSlowPeriod: indicatorSettings.macdSlowPeriod,
        macdSignalPeriod: indicatorSettings.macdSignalPeriod,
        stochasticKPeriod: indicatorSettings.stochasticKPeriod,
        stochasticDPeriod: indicatorSettings.stochasticDPeriod,
        stochasticSlowing: indicatorSettings.stochasticSlowing,
        rsiPeriod: indicatorSettings.rsiPeriod,
        rsiOversold: indicatorSettings.rsiOversold,
        rsiOverbought: indicatorSettings.rsiOverbought,
      };

      const backtestResult = await runBacktest(request);
      setResult(backtestResult);
      setChartTimeRange(undefined); // 시간 범위 초기화
    } catch (err: any) {
      console.error('❌ 백테스팅 오류:', err);
      setError(err.message || '백테스팅 실행 중 오류가 발생했습니다.');
    } finally {
      setLoading(false);
    }
  }, [cursor, loading, selectedStrategy, symbol, period, timeframe, initialCapital]);

  const formatDateForInput = (date: Date): string => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  const handleRunBacktest = async () => {
    if (!selectedStrategy || !symbol) {
      setError('전략과 종목을 선택해주세요.');
      return;
    }

    setLoading(true);
    setError('');
    setResult(null);
    setCursor(0); // 새 백테스팅 시 커서 초기화

    try {
      const { startDate, endDate } = calculateDateRange(period, 0);
      
      // 보조지표 설정 가져오기
      const indicatorSettings = loadIndicatorSettings();
      
      const request: BacktestRequest = {
        symbol,
        strategyId: Number(selectedStrategy),
        startDate,
        endDate,
        initialCapital,
        positionSizeRatio: 1.0,
        commissionRate: 0.0005,
        timeframe,
        // 보조지표 파라미터 (설정 > 보조지표 설정에서 동기화)
        macdFastPeriod: indicatorSettings.macdFastPeriod,
        macdSlowPeriod: indicatorSettings.macdSlowPeriod,
        macdSignalPeriod: indicatorSettings.macdSignalPeriod,
        stochasticKPeriod: indicatorSettings.stochasticKPeriod,
        stochasticDPeriod: indicatorSettings.stochasticDPeriod,
        stochasticSlowing: indicatorSettings.stochasticSlowing,
        rsiPeriod: indicatorSettings.rsiPeriod,
        rsiOversold: indicatorSettings.rsiOversold,
        rsiOverbought: indicatorSettings.rsiOverbought,
      };

      const backtestResult = await runBacktest(request);
      setResult(backtestResult);
    } catch (err: any) {
      console.error('백테스팅 실행 실패:', err);
      setError(err.response?.data?.message || '백테스팅 실행 중 오류가 발생했습니다.');
    } finally {
      setLoading(false);
    }
  };

  // 시간봉 변경 핸들러 - 변경된 시간봉으로 백테스팅 재수행
  const handleIntervalChange = async (newInterval: string) => {
    if (!newInterval || newInterval === timeframe) return;
    
    // 시간봉 상태 업데이트
    setTimeframe(newInterval);
    
    // 결과가 있고, 전략과 종목이 선택되어 있으면 백테스팅 재수행
    if (result && selectedStrategy && symbol) {
      setLoading(true);
      setError('');
      setCursor(0); // 커서 초기화

      try {
        const { startDate, endDate } = calculateDateRange(period, 0);
        
        // 보조지표 설정 가져오기
        const indicatorSettings = loadIndicatorSettings();
        
        const request: BacktestRequest = {
          symbol,
          strategyId: Number(selectedStrategy),
          startDate,
          endDate,
          initialCapital,
          positionSizeRatio: 1.0,
          commissionRate: 0.0005,
          timeframe: newInterval, // 새로운 시간봉 사용
          // 보조지표 파라미터
          macdFastPeriod: indicatorSettings.macdFastPeriod,
          macdSlowPeriod: indicatorSettings.macdSlowPeriod,
          macdSignalPeriod: indicatorSettings.macdSignalPeriod,
          stochasticKPeriod: indicatorSettings.stochasticKPeriod,
          stochasticDPeriod: indicatorSettings.stochasticDPeriod,
          stochasticSlowing: indicatorSettings.stochasticSlowing,
          rsiPeriod: indicatorSettings.rsiPeriod,
          rsiOversold: indicatorSettings.rsiOversold,
          rsiOverbought: indicatorSettings.rsiOverbought,
        };

        console.log(`⏱️ 시간봉 변경: ${timeframe} → ${newInterval}, 백테스팅 재수행`);
        console.log(`📤 백테스팅 요청:`, { symbol, startDate, endDate, timeframe: newInterval });
        const backtestResult = await runBacktest(request);
        console.log(`📥 백테스팅 결과: candleData=${backtestResult.candleData?.length || 0}개, indicatorData=${backtestResult.indicatorData?.length || 0}개`);
        if (backtestResult.candleData && backtestResult.candleData.length > 0) {
          console.log(`📅 첫 번째 캔들: ${backtestResult.candleData[0].time}`);
          console.log(`📅 마지막 캔들: ${backtestResult.candleData[backtestResult.candleData.length - 1].time}`);
        }
        setResult(backtestResult);
      } catch (err: any) {
        console.error('시간봉 변경 백테스팅 실패:', err);
        setError(err.response?.data?.message || '백테스팅 실행 중 오류가 발생했습니다.');
      } finally {
        setLoading(false);
      }
    }
  };

  const handleReset = () => {
    setResult(null);
    setError('');
  };

  // 차트 데이터 생성
  const generateChartData = () => {
    if (!result || !result.performanceHistory || result.performanceHistory.length === 0) {
      return null;
    }

    return {
      labels: result.performanceHistory.map((item) =>
        new Date(item.timestamp).toLocaleDateString('ko-KR', { month: 'numeric', day: 'numeric' }).replace('.', '월 ').replace('.', '일')
      ),
      datasets: [
        {
          label: '포트폴리오 가치',
          data: result.performanceHistory.map((item) => item.portfolioValue),
          borderColor: 'rgb(75, 192, 192)',
          backgroundColor: 'rgba(75, 192, 192, 0.2)',
          tension: 0.3,
          fill: true,
          pointRadius: 0,
          pointHoverRadius: 4,
          borderWidth: 2,
        },
      ],
    };
  };

  const chartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        position: 'top' as const,
      },
      title: {
        display: true,
        text: '포트폴리오 가치 변화',
      },
    },
    scales: {
      x: {
        ticks: {
          maxTicksLimit: 12,
          maxRotation: 0,
          minRotation: 0,
        },
        grid: {
          display: false,
        },
      },
      y: {
        beginAtZero: false,
        ticks: {
          callback: (value: any) => `₩${value.toLocaleString()}`,
          maxTicksLimit: 8,
        },
        grid: {
          color: 'rgba(0, 0, 0, 0.1)',
        },
      },
    },
  };

  return (
    <Box sx={{ width: '100%', p: isChartFullscreen ? 0 : 3 }}>
      {/* 헤더 및 설정 영역 - 전체화면 시 숨김 */}
      {!isChartFullscreen && (
        <>
          <Typography variant="h4" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <Assessment />
            전략 백테스팅
          </Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
            과거 데이터를 사용하여 투자 전략의 성과를 시뮬레이션합니다.
          </Typography>

          {/* 현재 적용된 보조지표 설정 안내 */}
          {(() => {
            const indicatorSettings = loadIndicatorSettings();
            return (
              <Alert severity="info" sx={{ mb: 2 }}>
                <Typography variant="body2">
                  📊 <strong>현재 보조지표 설정</strong>: 
                  MACD({indicatorSettings.macdFastPeriod}, {indicatorSettings.macdSlowPeriod}, {indicatorSettings.macdSignalPeriod}) / 
                  Stochastic Slow({indicatorSettings.stochasticKPeriod}, {indicatorSettings.stochasticDPeriod}, {indicatorSettings.stochasticSlowing}) / 
                  RSI({indicatorSettings.rsiPeriod}, 과매도:{indicatorSettings.rsiOversold}, 과매수:{indicatorSettings.rsiOverbought})
                  &nbsp;&nbsp;
                  <Typography component="span" variant="body2" color="text.secondary">
                    (설정 → 보조지표 설정에서 변경 가능)
                  </Typography>
                </Typography>
              </Alert>
            );
          })()}

          {/* 입력 폼 */}
          <Paper elevation={2} sx={{ p: 3, mb: 3 }}>
        <Typography variant="h6" gutterBottom>
          백테스팅 설정
        </Typography>
        <Grid container spacing={2}>
          <Grid item xs={12} md={6}>
            <FormControl fullWidth>
              <InputLabel>전략 선택</InputLabel>
              <Select
                value={selectedStrategy}
                label="전략 선택"
                onChange={(e) => setSelectedStrategy(e.target.value as number)}
                onOpen={loadStrategies}
              >
                {strategies.length === 0 ? (
                  <MenuItem value="" disabled>
                    활성화된 전략이 없습니다
                  </MenuItem>
                ) : (
                  strategies.map((strategy) => (
                    <MenuItem key={strategy.id} value={strategy.id}>
                      {strategy.name} ({strategy.strategyType})
                    </MenuItem>
                  ))
                )}
              </Select>
              {strategies.length === 0 && (
                <Typography variant="caption" color="error" sx={{ mt: 0.5 }}>
                  ⚠️ 설정 → 투자전략에서 전략을 활성화해주세요
                </Typography>
              )}
            </FormControl>
          </Grid>
          <Grid item xs={12} md={6}>
            <FormControl fullWidth>
              <InputLabel>종목 선택</InputLabel>
              <Select
                value={symbol}
                label="종목 선택"
                onChange={(e) => setSymbol(e.target.value)}
              >
                {cryptoList.map((crypto) => (
                  <MenuItem key={crypto.symbol} value={crypto.symbol}>
                    {crypto.koreanName} ({crypto.symbol})
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Grid>
          <Grid item xs={12} md={4}>
            <FormControl fullWidth>
              <InputLabel>시간 선택</InputLabel>
              <Select
                value={timeframe}
                label="시간 선택"
                onChange={(e) => setTimeframe(e.target.value)}
              >
                <MenuItem value="3m">3분봉</MenuItem>
                <MenuItem value="5m">5분봉</MenuItem>
                <MenuItem value="10m">10분봉</MenuItem>
                <MenuItem value="15m">15분봉</MenuItem>
                <MenuItem value="30m">30분봉</MenuItem>
                <MenuItem value="1h">1시간봉</MenuItem>
                <MenuItem value="4h">4시간봉</MenuItem>
                <MenuItem value="1d">일봉</MenuItem>
                <MenuItem value="1w">주봉</MenuItem>
              </Select>
            </FormControl>
          </Grid>
          <Grid item xs={12} md={4}>
            <FormControl fullWidth>
              <InputLabel>분석기간</InputLabel>
              <Select
                value={period}
                label="분석기간"
                onChange={(e) => setPeriod(e.target.value)}
              >
                <MenuItem value="1day">1일</MenuItem>
                <MenuItem value="1week">일주일</MenuItem>
                <MenuItem value="10days">10일</MenuItem>
                <MenuItem value="15days">15일</MenuItem>
                <MenuItem value="1month">1개월</MenuItem>
                <MenuItem value="3months">3개월</MenuItem>
                <MenuItem value="6months">6개월</MenuItem>
              </Select>
            </FormControl>
          </Grid>
          <Grid item xs={12} md={4}>
            <TextField
              fullWidth
              label="초기 자본금"
              type="number"
              value={initialCapital}
              onChange={(e) => setInitialCapital(Number(e.target.value))}
              InputProps={{
                startAdornment: <Typography sx={{ mr: 1 }}>₩</Typography>,
              }}
            />
          </Grid>
          <Grid item xs={12}>
            <Box sx={{ display: 'flex', gap: 2 }}>
              <Button
                variant="contained"
                color="primary"
                startIcon={loading ? <CircularProgress size={20} /> : <PlayArrow />}
                onClick={handleRunBacktest}
                disabled={loading}
                fullWidth
              >
                {loading ? '백테스팅 실행 중...' : '백테스팅 시작'}
              </Button>
              <Button variant="outlined" startIcon={<Refresh />} onClick={handleReset}>
                초기화
              </Button>
            </Box>
          </Grid>
        </Grid>
          </Paper>
        </>
      )}

      {/* 에러 메시지 - 전체화면 시 숨김 */}
      {!isChartFullscreen && error && (
        <Alert severity="error" sx={{ mb: 3 }}>
          {error}
        </Alert>
      )}

      {/* 결과 표시 */}
      {result && (
        <>
          {/* 요약 통계 - 전체화면 시 숨김 */}
          <Paper elevation={2} sx={{ p: 3, mb: 3, display: isChartFullscreen ? 'none' : 'block' }}>
            <Typography variant="h6" gutterBottom>
              📊 성과 요약
            </Typography>
            <Grid container spacing={2}>
              <Grid item xs={12} sm={6} md={3}>
                <Card variant="outlined">
                  <CardContent>
                    <Typography color="text.secondary" gutterBottom>
                      초기 자본
                    </Typography>
                    <Typography variant="h6">
                      ₩{Math.round(result.initialCapital).toLocaleString()}
                    </Typography>
                  </CardContent>
                </Card>
              </Grid>
              <Grid item xs={12} sm={6} md={3}>
                <Card variant="outlined">
                  <CardContent>
                    <Typography color="text.secondary" gutterBottom>
                      최종 자본
                    </Typography>
                    <Typography variant="h6">
                      ₩{Math.round(result.finalCapital).toLocaleString()}
                    </Typography>
                  </CardContent>
                </Card>
              </Grid>
              <Grid item xs={12} sm={6} md={3}>
                <Card variant="outlined" sx={{ bgcolor: result.netProfit >= 0 ? 'success.light' : 'error.light' }}>
                  <CardContent>
                    <Typography color="text.secondary" gutterBottom>
                      순수익
                    </Typography>
                    <Typography variant="h6" sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                      {result.netProfit >= 0 ? <TrendingUp /> : <TrendingDown />}
                      ₩{Math.round(result.netProfit).toLocaleString()}
                    </Typography>
                  </CardContent>
                </Card>
              </Grid>
              <Grid item xs={12} sm={6} md={3}>
                <Card variant="outlined" sx={{ bgcolor: result.returnRate >= 0 ? 'success.light' : 'error.light' }}>
                  <CardContent>
                    <Typography color="text.secondary" gutterBottom>
                      수익률
                    </Typography>
                    <Typography variant="h6">
                      {result.returnRate.toFixed(2)}%
                    </Typography>
                  </CardContent>
                </Card>
              </Grid>
            </Grid>

            <Divider sx={{ my: 2 }} />

            <Grid container spacing={2}>
              <Grid item xs={6} sm={4} md={2}>
                <Typography variant="body2" color="text.secondary">총 거래</Typography>
                <Typography variant="h6">{result.totalTrades}회</Typography>
              </Grid>
              <Grid item xs={6} sm={4} md={2}>
                <Typography variant="body2" color="text.secondary">매수</Typography>
                <Typography variant="h6" color="primary">{result.buyCount}회</Typography>
              </Grid>
              <Grid item xs={6} sm={4} md={2}>
                <Typography variant="body2" color="text.secondary">매도</Typography>
                <Typography variant="h6" color="secondary">{result.sellCount}회</Typography>
              </Grid>
              <Grid item xs={6} sm={4} md={2}>
                <Typography variant="body2" color="text.secondary">승률</Typography>
                <Typography variant="h6">{result.winRate.toFixed(2)}%</Typography>
              </Grid>
              <Grid item xs={6} sm={4} md={2}>
                <Typography variant="body2" color="text.secondary">MDD</Typography>
                <Tooltip title="Maximum Drawdown (최대 낙폭)">
                  <Typography variant="h6" color="error">{result.maxDrawdown.toFixed(2)}%</Typography>
                </Tooltip>
              </Grid>
              <Grid item xs={6} sm={4} md={2}>
                <Typography variant="body2" color="text.secondary">샤프 비율</Typography>
                <Tooltip title="위험 대비 수익률">
                  <Typography variant="h6">{result.sharpeRatio.toFixed(4)}</Typography>
                </Tooltip>
              </Grid>
            </Grid>
          </Paper>

          {/* 캔들차트 - 일반 모드 */}
          {result.candleData && result.candleData.length > 0 && !isChartFullscreen && (
            <Paper elevation={2} sx={{ p: 3, mb: 3 }}>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 2 }}>
                <Typography variant="h6" sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <ShowChart />
                  주가 캔들차트 (매수/매도 시점 포함)
                </Typography>
              </Box>
              
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', mb: 1 }}>
                {/* 현재 분석 기간 표시 */}
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
                  {cursor !== 0 && (
                    <Chip 
                      label={`${Math.abs(cursor)} 기간 전`} 
                      color="info" 
                      size="small"
                      sx={{ fontWeight: 'bold' }}
                    />
                  )}
                  <Typography variant="body2" color="text.secondary">
                    {(() => {
                      const { startDate, endDate } = calculateDateRange(period, cursor);
                      const start = new Date(startDate).toLocaleDateString('ko-KR');
                      const end = new Date(endDate).toLocaleDateString('ko-KR');
                      return `${start} ~ ${end}`;
                    })()}
                  </Typography>
                  <Tooltip title="◀ 과거 / ▶ 현재 방향으로 이동">
                    <Info fontSize="small" color="action" />
                  </Tooltip>
                </Box>
              </Box>
              <Box sx={{ mt: 2 }}>
                <MacdChart 
                  data={convertToMacdResult(result.candleData, result.indicatorData)}
                  title={`${result.strategyName} - ${symbol}`}
                  interval={timeframe}
                  onIntervalChange={handleIntervalChange}
                  showLeftButton={cursor < 0 || true}
                  showRightButton={cursor < 0}
                  isFullscreen={isChartFullscreen}
                  onToggleFullscreen={handleToggleFullscreen}
                />
              </Box>
              {/* 범례 영역 + 좌우 화살표 버튼 */}
              <Box sx={{ 
                display: 'flex', 
                alignItems: 'center', 
                justifyContent: 'space-between', 
                mt: 2,
                px: 1
              }}>
                {/* 왼쪽 화살표 버튼 (과거로 이동) */}
                <IconButton
                  onClick={() => handleChartNavigate('past')}
                  disabled={loading}
                  sx={{
                    bgcolor: 'action.hover',
                    borderRadius: 1,
                    px: 1.5,
                    py: 0.5,
                    '&:hover': {
                      bgcolor: 'primary.light',
                      color: 'white',
                    },
                    '&:disabled': {
                      bgcolor: 'action.disabledBackground',
                    },
                  }}
                >
                  {loading ? (
                    <CircularProgress size={16} />
                  ) : (
                    <Typography sx={{ fontSize: 18, fontWeight: 'bold' }}>◀ 이전</Typography>
                  )}
                </IconButton>

                {/* 중앙 범례 */}
                <Box sx={{ display: 'flex', gap: 3, justifyContent: 'center', flexWrap: 'wrap' }}>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Box sx={{ width: 20, height: 20, bgcolor: '#2196F3', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                      <Typography sx={{ color: 'white', fontSize: '12px' }}>↑</Typography>
                    </Box>
                    <Typography variant="body2">매수 시점</Typography>
                  </Box>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Box sx={{ width: 20, height: 20, bgcolor: '#f44336', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                      <Typography sx={{ color: 'white', fontSize: '12px' }}>↓</Typography>
                    </Box>
                    <Typography variant="body2">매도 시점</Typography>
                  </Box>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Box sx={{ width: 20, height: 2, bgcolor: colors.ma12 }} />
                    <Typography variant="body2">MA12 (12일선)</Typography>
                  </Box>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Box sx={{ width: 20, height: 2, bgcolor: colors.ma26 }} />
                    <Typography variant="body2">MA26 (26일선)</Typography>
                  </Box>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Box sx={{ width: 20, height: 2, bgcolor: colors.ma60 }} />
                    <Typography variant="body2">MA60 (60일선)</Typography>
                  </Box>
                </Box>

                {/* 오른쪽 화살표 버튼 (현재로 이동) */}
                <IconButton
                  onClick={() => handleChartNavigate('future')}
                  disabled={loading || cursor >= 0}
                  sx={{
                    bgcolor: cursor < 0 ? 'action.hover' : 'transparent',
                    borderRadius: 1,
                    px: 1.5,
                    py: 0.5,
                    visibility: cursor < 0 ? 'visible' : 'hidden',
                    '&:hover': {
                      bgcolor: 'primary.light',
                      color: 'white',
                    },
                    '&:disabled': {
                      bgcolor: 'action.disabledBackground',
                    },
                  }}
                >
                  {loading ? (
                    <CircularProgress size={16} />
                  ) : (
                    <Typography sx={{ fontSize: 18, fontWeight: 'bold' }}>다음 ▶</Typography>
                  )}
                </IconButton>
              </Box>
            </Paper>
          )}
          
          {/* 캔들차트 - 전체화면 모드 */}
          {result.candleData && result.candleData.length > 0 && isChartFullscreen && (
            <Box
              sx={{
                position: 'fixed',
                top: 64, // 상단 메뉴바 높이
                left: 0,
                right: 0,
                bottom: 0,
                zIndex: 1200,
                bgcolor: 'background.paper',
                p: 2,
                overflow: 'auto',
              }}
            >
              <Box sx={{ height: '100%' }}>
                <MacdChart 
                  data={convertToMacdResult(result.candleData, result.indicatorData)}
                  title={`${result.strategyName} - ${symbol}`}
                  interval={timeframe}
                  onIntervalChange={handleIntervalChange}
                  showLeftButton={cursor < 0 || true}
                  showRightButton={cursor < 0}
                  isFullscreen={isChartFullscreen}
                  onToggleFullscreen={handleToggleFullscreen}
                />
              </Box>
            </Box>
          )}

          {/* ===== 기존 전략 기반 차트 (하위 호환성 유지) - 전체화면 시 숨김 ===== */}

          {/* TREND_STOCHASTIC / TREND_STOCHASTIC_CCI / STOCHASTIC_ONLY 전략: Stochastic Slow 차트 (분리) */}
          {!isChartFullscreen && result.indicatorData && result.indicatorData.length > 0 && 
           !indicatorSettings.stochasticSlow &&
           (result.strategyType === 'TREND_STOCHASTIC' ||
            result.strategyType === 'TREND_STOCHASTIC_CCI' ||
            result.strategyType === 'STOCHASTIC_ONLY' ||
            result.strategyName.includes('Stochastic Slow') || 
            result.strategyName.includes('추세 기반') ||
            result.strategyName.includes('CCI 기반')) && (
            <Paper elevation={2} sx={{ p: 3, mb: 3 }}>
              <Typography variant="h6" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <ShowChart />
                Stochastic Slow 차트
              </Typography>
              <Box sx={{ mt: 2 }}>
                <MacdChart 
                  data={result.indicatorData}
                  candleData={result.candleData}
                />
              </Box>
              
              {/* Stochastic 범례 (업비트 스타일) */}
              <Box sx={{ display: 'flex', gap: 3, mt: 2, justifyContent: 'center', flexWrap: 'wrap' }}>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Box sx={{ width: 20, height: 2, bgcolor: '#FF9500' }} />
                  <Typography variant="body2">%K (주황)</Typography>
                </Box>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Box sx={{ width: 20, height: 2, bgcolor: '#2196F3' }} />
                  <Typography variant="body2">%D (파랑)</Typography>
                </Box>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Box sx={{ width: 20, height: 8, bgcolor: 'rgba(239, 83, 80, 0.1)', border: '1px dashed rgba(239, 83, 80, 0.6)' }} />
                  <Typography variant="body2">과매수 (80 이상)</Typography>
                </Box>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Box sx={{ width: 20, height: 8, bgcolor: 'rgba(33, 150, 243, 0.1)', border: '1px dashed rgba(33, 150, 243, 0.6)' }} />
                  <Typography variant="body2">과매도 (20 이하)</Typography>
                </Box>
              </Box>
            </Paper>
          )}

          {/* TREND_STOCHASTIC / STOCHASTIC_ONLY 전략: MACD 차트 (분리) - macdLine 설정이 OFF일 때만 */}
          {!isChartFullscreen && result.indicatorData && result.indicatorData.length > 0 && 
           !indicatorSettings.macdLine &&
           (result.strategyType === 'TREND_STOCHASTIC' ||
            result.strategyType === 'STOCHASTIC_ONLY' ||
            result.strategyName.includes('Stochastic Slow') || 
            result.strategyName.includes('추세 기반')) &&
           result.strategyType !== 'TREND_STOCHASTIC_CCI' && (
            <Paper elevation={2} sx={{ p: 3, mb: 3 }}>
              <Typography variant="h6" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <ShowChart />
                MACD 차트
              </Typography>
              <Box sx={{ mt: 2 }}>
                <MacdChart 
                  data={result.indicatorData}
                  candleData={result.candleData}
                />
              </Box>
              
              {/* MACD 범례 (업비트 스타일) */}
              <Box sx={{ display: 'flex', gap: 3, mt: 2, justifyContent: 'center', flexWrap: 'wrap' }}>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Box sx={{ width: 20, height: 2, bgcolor: '#2962FF' }} />
                  <Typography variant="body2">MACD (파랑)</Typography>
                </Box>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Box sx={{ width: 20, height: 2, bgcolor: '#FF9800' }} />
                  <Typography variant="body2">Signal (주황)</Typography>
                </Box>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Box sx={{ width: 8, height: 12, bgcolor: 'rgba(198, 40, 40, 0.8)' }} />
                  <Typography variant="body2">양수 (빨강)</Typography>
                </Box>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Box sx={{ width: 8, height: 12, bgcolor: 'rgba(21, 101, 192, 0.8)' }} />
                  <Typography variant="body2">음수 (파랑)</Typography>
                </Box>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Box sx={{ width: 20, height: 1, bgcolor: 'rgba(128, 128, 128, 0.5)', borderStyle: 'dashed' }} />
                  <Typography variant="body2">Zero Line</Typography>
                </Box>
              </Box>
            </Paper>
          )}

          {/* TREND_STOCHASTIC_CCI 전략: CCI 차트 (분리) - cci13 설정이 OFF일 때만 */}
          {!isChartFullscreen && result.indicatorData && result.indicatorData.length > 0 && 
           !indicatorSettings.cci &&
           (result.strategyType === 'TREND_STOCHASTIC_CCI' ||
            result.strategyName.includes('CCI 기반')) && (
            <Paper elevation={2} sx={{ p: 3, mb: 3 }}>
              <Typography variant="h6" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <ShowChart />
                CCI 차트
              </Typography>
              <Box sx={{ mt: 2 }}>
                <MacdChart 
                  data={result.indicatorData}
                  candleData={result.candleData}
                />
              </Box>
              
              {/* CCI 범례 */}
              <Box sx={{ display: 'flex', gap: 3, mt: 2, justifyContent: 'center', flexWrap: 'wrap' }}>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Box sx={{ width: 20, height: 2, bgcolor: '#9C27B0' }} />
                  <Typography variant="body2">CCI (보라)</Typography>
                </Box>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Box sx={{ width: 20, height: 8, bgcolor: 'rgba(239, 83, 80, 0.1)', border: '1px dashed rgba(239, 83, 80, 0.6)' }} />
                  <Typography variant="body2">과매수 (100 이상)</Typography>
                </Box>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Box sx={{ width: 20, height: 8, bgcolor: 'rgba(33, 150, 243, 0.1)', border: '1px dashed rgba(33, 150, 243, 0.6)' }} />
                  <Typography variant="body2">과매도 (-100 이하)</Typography>
                </Box>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Box sx={{ width: 20, height: 1, bgcolor: 'rgba(128, 128, 128, 0.5)', borderStyle: 'dashed' }} />
                  <Typography variant="body2">Zero Line</Typography>
                </Box>
              </Box>
            </Paper>
          )}

          {/* 기타 전략: 통합 지표 차트 */}
          {!isChartFullscreen && result.indicatorData && result.indicatorData.length > 0 && 
           result.strategyType !== 'TREND_STOCHASTIC' &&
           result.strategyType !== 'TREND_STOCHASTIC_CCI' &&
           result.strategyType !== 'STOCHASTIC_ONLY' &&
           !result.strategyName.includes('Stochastic Slow') && 
           !result.strategyName.includes('추세 기반') &&
           !result.strategyName.includes('CCI 기반') && (
            <Paper elevation={2} sx={{ p: 3, mb: 3 }}>
              <Typography variant="h6" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <ShowChart />
                {result.strategyName} - 지표 차트
              </Typography>
              <Box sx={{ mt: 2 }}>
                <MacdChart 
                  data={result.indicatorData}
                  candleData={result.candleData}
                />
              </Box>
              
              {/* MACD 기반 전략 범례 */}
              {(result.strategyName.includes('MACD') || result.strategyName.includes('1') || 
                result.strategyName.includes('2') || result.strategyName.includes('3') || 
                result.strategyName.includes('4') || result.strategyName.includes('5')) && (
                <Box sx={{ display: 'flex', gap: 3, mt: 2, justifyContent: 'center', flexWrap: 'wrap' }}>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Box sx={{ width: 20, height: 3, bgcolor: '#c62828' }} />
                    <Typography variant="body2">MACD Line (짙은 빨강)</Typography>
                  </Box>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Box sx={{ width: 20, height: 3, bgcolor: '#FF9800' }} />
                    <Typography variant="body2">Signal Line (주황)</Typography>
                  </Box>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Box sx={{ width: 20, height: 10, bgcolor: 'rgba(0, 150, 136, 0.8)' }} />
                    <Typography variant="body2">Histogram (양수: 청록, 음수: 빨강)</Typography>
                  </Box>
                  {(!result.strategyName.includes('1') && !result.strategyName.includes('5')) && (
                    <>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <Box sx={{ width: 20, height: 3, bgcolor: '#c62828' }} />
                        <Typography variant="body2">Stochastic %K (짙은 빨강)</Typography>
                      </Box>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <Box sx={{ width: 20, height: 3, bgcolor: '#1565C0' }} />
                        <Typography variant="body2">Stochastic %D (짙은 파랑)</Typography>
                      </Box>
                    </>
                  )}
                  {(result.strategyName.includes('3') || result.strategyName.includes('4')) && (
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <Box sx={{ width: 20, height: 3, bgcolor: '#4CAF50' }} />
                      <Typography variant="body2">ADX</Typography>
                    </Box>
                  )}
                  {result.strategyName.includes('4') && (
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <Box sx={{ width: 20, height: 3, bgcolor: '#FF5722' }} />
                      <Typography variant="body2">CCI</Typography>
                    </Box>
                  )}
                </Box>
              )}
              
              {result.strategyName.includes('그랜빌') && (
                <Box sx={{ display: 'flex', gap: 3, mt: 2, justifyContent: 'center', flexWrap: 'wrap' }}>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Box sx={{ width: 20, height: 3, bgcolor: '#2196F3' }} />
                    <Typography variant="body2">MA10 (10일선)</Typography>
                  </Box>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Box sx={{ width: 20, height: 3, bgcolor: '#FF9800' }} />
                    <Typography variant="body2">MA20 (20일선)</Typography>
                  </Box>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Box sx={{ width: 20, height: 3, bgcolor: '#4CAF50' }} />
                    <Typography variant="body2">MA60 (60일선)</Typography>
                  </Box>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Box sx={{ width: 20, height: 3, bgcolor: '#9C27B0' }} />
                    <Typography variant="body2">MA200 (200일선)</Typography>
                  </Box>
                </Box>
              )}
              
              {result.strategyName.includes('OBV') && (
                <Box sx={{ display: 'flex', gap: 3, mt: 2, justifyContent: 'center', flexWrap: 'wrap' }}>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Box sx={{ width: 20, height: 3, bgcolor: '#2196F3' }} />
                    <Typography variant="body2">OBV (On Balance Volume)</Typography>
                  </Box>
                </Box>
              )}
              
              {result.strategyName.includes('심리선') && (
                <Box sx={{ display: 'flex', gap: 3, mt: 2, justifyContent: 'center', flexWrap: 'wrap' }}>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Box sx={{ width: 20, height: 3, bgcolor: '#2196F3' }} />
                    <Typography variant="body2">심리선 (%)</Typography>
                  </Box>
                </Box>
              )}
              
              {!result.strategyName.includes('MACD') && !result.strategyName.includes('그랜빌') && 
               !result.strategyName.includes('OBV') && !result.strategyName.includes('심리선') &&
               !result.strategyName.includes('1') && !result.strategyName.includes('2') &&
               !result.strategyName.includes('3') && !result.strategyName.includes('4') &&
               !result.strategyName.includes('5') && (
                <Box sx={{ display: 'flex', gap: 3, mt: 2, justifyContent: 'center', flexWrap: 'wrap' }}>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Box sx={{ width: 20, height: 3, bgcolor: '#2196F3' }} />
                    <Typography variant="body2">MA10 (10일선)</Typography>
                  </Box>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Box sx={{ width: 20, height: 3, bgcolor: '#FF9800' }} />
                    <Typography variant="body2">MA20 (20일선)</Typography>
                  </Box>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Box sx={{ width: 20, height: 3, bgcolor: '#4CAF50' }} />
                    <Typography variant="body2">MA60 (60일선)</Typography>
                  </Box>
                </Box>
              )}
            </Paper>
          )}

          {/* 포트폴리오 성과 차트 - 전체화면 시 숨김 */}
          {!isChartFullscreen && result.performanceHistory && result.performanceHistory.length > 0 && (
            <Paper elevation={2} sx={{ p: 3, mb: 3 }}>
              <Typography variant="h6" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <ShowChart />
                포트폴리오 가치 변화
              </Typography>
              <Box sx={{ height: 400 }}>
                <Line data={generateChartData()!} options={chartOptions} />
              </Box>
            </Paper>
          )}

          {/* 거래 내역 - 전체화면 시 숨김 */}
          {!isChartFullscreen && (
          <Paper elevation={2} sx={{ p: 3 }}>
            <Typography variant="h6" gutterBottom>
              거래 내역
            </Typography>
            <TableContainer sx={{ maxHeight: 600 }}>
              <Table stickyHeader size="small">
                <TableHead>
                  <TableRow>
                    <TableCell>시간</TableCell>
                    <TableCell>유형</TableCell>
                    <TableCell align="right">가격</TableCell>
                    <TableCell align="right">수량</TableCell>
                    <TableCell align="right">거래금액</TableCell>
                    <TableCell align="right">수익/손실</TableCell>
                    <TableCell align="right">수익률</TableCell>
                    <TableCell align="right">잔액</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {result.tradeRecords.map((trade, index) => (
                    <TableRow key={index} hover>
                      <TableCell>
                        {new Date(trade.timestamp).toLocaleString('ko-KR')}
                      </TableCell>
                      <TableCell>
                        <Chip
                          label={trade.tradeType}
                          size="small"
                          color={trade.tradeType === 'BUY' ? 'primary' : 'secondary'}
                        />
                      </TableCell>
                      <TableCell align="right">
                        ₩{trade.price.toLocaleString()}
                      </TableCell>
                      <TableCell align="right">
                        {trade.quantity.toFixed(8)}
                      </TableCell>
                      <TableCell align="right">
                        ₩{trade.totalAmount.toLocaleString()}
                      </TableCell>
                      <TableCell align="right" sx={{ color: trade.profitLoss && trade.profitLoss >= 0 ? 'success.main' : 'error.main' }}>
                        {trade.profitLoss ? `₩${trade.profitLoss.toLocaleString()}` : '-'}
                      </TableCell>
                      <TableCell align="right" sx={{ color: trade.returnRate && trade.returnRate >= 0 ? 'success.main' : 'error.main' }}>
                        {trade.returnRate ? `${trade.returnRate.toFixed(2)}%` : '-'}
                      </TableCell>
                      <TableCell align="right">
                        ₩{trade.balance.toLocaleString()}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          </Paper>
          )}
        </>
      )}

      {/* 종목 선택 패널 (좌측 하단 FAB) */}
      <CryptoListPanel
        currentSymbol={symbol}
        onSelectSymbol={(newSymbol) => {
          setSymbol(newSymbol);
          // 결과 초기화
          setResult(null);
          setCursor(0);
        }}
      />
    </Box>
  );
};

export default StrategyPage;

