import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import {
  Box,
  Typography,
  Button,
  CircularProgress,
  FormControl,
  Select,
  MenuItem,
  InputAdornment,
  useTheme,
  TextField,
  Tabs,
  Tab,
  useMediaQuery,
  Drawer,
  IconButton,
  Card,
  CardContent,
  Fab,
  SwipeableDrawer,
  Collapse,
  Chip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Table,
  TableBody,
  TableCell,
  TableRow,
  Tooltip,
  Paper,
  Grid,
} from '@mui/material';
import {
  PlayArrow,
  ChevronLeft,
  ChevronRight,
  Menu as MenuIcon,
  Close as CloseIcon,
  Settings as SettingsIcon,
  Assessment as AssessmentIcon,
  TrendingUp,
  TrendingDown,
  ExpandMore,
  ExpandLess,
} from '@mui/icons-material';
import { runBacktest, BacktestResult, BacktestRequest, CandleData, IndicatorData, TradeRecord } from '../services/backtestApi';
import { getStrategyRules, StrategyRuleDto, TrendType } from '../services/strategyRuleApi';
import { analyzeSignals, SignalAnalysisRequest, CandleSignal } from '../services/strategySignalApi';
import CandlestickChart, { ChartHandle } from '../components/CandlestickChart';
import IndicatorChart, { IndicatorChartHandle } from '../components/IndicatorChart';
import CryptoNameComboBox from '../components/CryptoNameComboBox';
import { MacdResult } from '../types/stock';
import { loadIndicatorSettings } from '../components/settings/IndicatorSettingsTab';
import { useUITheme, UIThemeId, UIThemeStyle } from '../contexts/UIThemeContext';
import { useIndicatorVisibility } from '../contexts/IndicatorVisibilityContext';
import { useIndicatorSettings } from '../contexts/IndicatorSettingsContext';
import { useChartColors } from '../contexts/ChartColorContext';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, ResponsiveContainer, ReferenceLine, ComposedChart, Bar, Cell, ReferenceDot } from 'recharts';
import type { Time } from 'lightweight-charts';

/**
 * 모의투자 페이지 - 반응형 & 테마 지원
 */
// sessionStorage 키
const STORAGE_KEY = 'simulation_state';

// 저장된 상태 불러오기
const loadSavedState = () => {
  try {
    const saved = sessionStorage.getItem(STORAGE_KEY);
    if (saved) {
      return JSON.parse(saved);
    }
  } catch (e) {
    console.error('상태 복원 실패:', e);
  }
  return null;
};

const SimulationPage: React.FC = () => {
  const theme = useTheme();
  const { currentThemeId, currentDevice, currentThemeStyle, currentThemeInfo } = useUITheme();
  
  // MUI 테마 기반으로 다크 모드 결정 (다른 탭과 일관성 유지)
  const isDark = theme.palette.mode === 'dark';
  
  // MUI 테마 색상을 사용하여 다른 탭과 일관된 스타일 적용
  const themeStyle = {
    ...currentThemeStyle,
    backgroundColor: theme.palette.background.default,
    surfaceColor: theme.palette.background.paper,
    textColor: theme.palette.text.primary,
    textSecondaryColor: theme.palette.text.secondary,
    borderColor: isDark ? '#27272a' : '#e0e0e0',
    primaryColor: currentThemeStyle.primaryColor,
    accentColor: currentThemeStyle.accentColor,
  };
  
  // 테마 변경 디버깅 로그 (필요시 주석 해제)
  // console.log('🎨 SimulationPage 테마:', {
  //   currentThemeId,
  //   currentDevice,
  //   isDark,
  //   primaryColor: themeStyle.primaryColor,
  //   backgroundColor: themeStyle.backgroundColor,
  // });
  
  // 반응형 브레이크포인트
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));
  const isTablet = useMediaQuery(theme.breakpoints.between('sm', 'md'));
  const isDesktop = useMediaQuery(theme.breakpoints.up('md'));
  
  // 저장된 상태 불러오기
  const savedState = loadSavedState();
  
  // 전략관리 규칙 목록
  const [strategyRules, setStrategyRules] = useState<StrategyRuleDto[]>([]);
  const [uptrendStrategy, setUptrendStrategy] = useState<number | ''>(savedState?.uptrendStrategy || '');
  const [downtrendStrategy, setDowntrendStrategy] = useState<number | ''>(savedState?.downtrendStrategy || '');
  
  const [symbol, setSymbol] = useState<string>(savedState?.symbol || 'KRW-BTC');
  const [timeframe, setTimeframe] = useState<string>(savedState?.timeframe || '1h');
  const [period, setPeriod] = useState<string>(savedState?.period || '1month');
  const [initialCapital, setInitialCapital] = useState<number>(savedState?.initialCapital || 10000000);
  const [loading, setLoading] = useState<boolean>(false);
  const [isPeriodLoading, setIsPeriodLoading] = useState<boolean>(false); // ✅ 기간 변경 로딩 상태 (차트 유지)
  const [result, setResult] = useState<BacktestResult | null>(null);
  const [error, setError] = useState<string>('');
  const [rightPanelTab, setRightPanelTab] = useState<number>(savedState?.rightPanelTab || 0);
  const [leftPanelOpen, setLeftPanelOpen] = useState<boolean>(savedState?.leftPanelOpen ?? true);
  const [rightPanelOpen, setRightPanelOpen] = useState<boolean>(savedState?.rightPanelOpen ?? true);
  const [periodOffset, setPeriodOffset] = useState<number>(savedState?.periodOffset || 0);
  
  // ✅ 차트 refs
  const chartRef = useRef<ChartHandle>(null);
  const volumeChartRef = useRef<IndicatorChartHandle>(null);
  const newPsychologicalChartRef = useRef<IndicatorChartHandle>(null);
  const investPsychologicalChartRef = useRef<IndicatorChartHandle>(null);
  const macdChartRef = useRef<IndicatorChartHandle>(null);
  const cciChartRef = useRef<IndicatorChartHandle>(null);
  const adxChartRef = useRef<IndicatorChartHandle>(null);
  const bwiChartRef = useRef<IndicatorChartHandle>(null);
  const dmiChartRef = useRef<IndicatorChartHandle>(null);
  const obvChartRef = useRef<IndicatorChartHandle>(null);
  const rsiChartRef = useRef<IndicatorChartHandle>(null);
  const stochasticChartRef = useRef<IndicatorChartHandle>(null);
  const williamsRChartRef = useRef<IndicatorChartHandle>(null);
  const trixChartRef = useRef<IndicatorChartHandle>(null);
  const volumeOscChartRef = useRef<IndicatorChartHandle>(null);
  const vrChartRef = useRef<IndicatorChartHandle>(null);
  const disparityChartRef = useRef<IndicatorChartHandle>(null);
  
  // ✅ 크로스헤어 동기화 상태
  const [sharedHoverTime, setSharedHoverTime] = useState<string | null>(null);
  
  // ✅ Context hooks
  const indicatorVisibility = useIndicatorVisibility();
  const indicatorSettings = useIndicatorSettings();
  const chartColors = useChartColors();
  
  // 추세 판단 전략 설정
  type TrendStrategy = 'aggressive' | 'balanced' | 'conservative';
  const [trendStrategy, setTrendStrategy] = useState<TrendStrategy>(savedState?.trendStrategy || 'balanced');
  
  // 추세 전략에 따른 MA 값
  const getTrendMAs = (strategy: TrendStrategy) => {
    switch (strategy) {
      case 'aggressive':
        return { short: 5, medium: 10, long: 20 };
      case 'balanced':
        return { short: 10, medium: 20, long: 60 };
      case 'conservative':
        return { short: 20, medium: 60, long: 120 };
    }
  };
  
  const trendMAs = getTrendMAs(trendStrategy);
  const trendShortMA = trendMAs.short;
  const trendMediumMA = trendMAs.medium;
  const trendLongMA = trendMAs.long;
  
  // 모바일/태블릿용 드로어 상태
  const [mobileSettingsOpen, setMobileSettingsOpen] = useState(false);
  const [mobileResultsOpen, setMobileResultsOpen] = useState(false);
  const [mobileActiveTab, setMobileActiveTab] = useState<'settings' | 'chart' | 'results'>('chart');
  
  // 컴팩트 모드용 확장 상태
  const [settingsExpanded, setSettingsExpanded] = useState(true);
  const [resultsExpanded, setResultsExpanded] = useState(true);

  // 모달리스 팝업 상태 (opacity: 0 = 완전 불투명, 1 = 완전 투명)
  const [performancePopupOpen, setPerformancePopupOpen] = useState(false);
  const [tradeHistoryPopupOpen, setTradeHistoryPopupOpen] = useState(false);
  const [performancePopupPos, setPerformancePopupPos] = useState({ x: 100, y: 100 });
  const [tradeHistoryPopupPos, setTradeHistoryPopupPos] = useState({ x: 150, y: 150 });
  const [performancePopupOpacity, setPerformancePopupOpacity] = useState(0); // 0 = 불투명
  const [tradeHistoryPopupOpacity, setTradeHistoryPopupOpacity] = useState(0); // 0 = 불투명
  
  // 팝업 크기 상태
  const [performancePopupSize, setPerformancePopupSize] = useState({ width: 340, height: 520 });
  const [tradeHistoryPopupSize, setTradeHistoryPopupSize] = useState({ width: 400, height: 480 });
  
  // 리사이즈 상태
  const [perfResizing, setPerfResizing] = useState(false);
  const [tradeResizing, setTradeResizing] = useState(false);
  const perfResizeStart = useRef({ x: 0, y: 0, width: 340, height: 520 });
  const tradeResizeStart = useRef({ x: 0, y: 0, width: 400, height: 480 });
  
  // 거래 상세 정보 팝업 상태
  const [tradeDetailOpen, setTradeDetailOpen] = useState(false);
  const [selectedTrade, setSelectedTrade] = useState<TradeRecord | null>(null);
  
  // 거래 상세 정보 팝업 핸들러
  const handleTradeDoubleClick = (trade: TradeRecord) => {
    setSelectedTrade(trade);
    setTradeDetailOpen(true);
  };
  
  // 차트 마커 클릭 핸들러 (timestamp로 거래 기록 찾기)
  const handleMarkerClick = useCallback((timestamp: string, tradeType: 'BUY' | 'SELL') => {
    if (!result?.tradeRecords) return;
    
    // timestamp와 tradeType으로 해당 거래 기록 찾기
    const trade = result.tradeRecords.find(t => {
      // 정확한 매칭
      if (t.timestamp === timestamp && t.tradeType === tradeType) return true;
      // T와 공백 변환 매칭
      if (t.timestamp?.replace('T', ' ') === timestamp.replace('T', ' ') && t.tradeType === tradeType) return true;
      return false;
    });
    
    if (trade) {
      setSelectedTrade(trade);
      setTradeDetailOpen(true);
    } else {
      console.log('거래 기록을 찾을 수 없습니다:', { timestamp, tradeType });
    }
  }, [result?.tradeRecords]);

  // ✅ 캔들차트 → 모든 보조지표 크로스헤어 동기화
  const handleCandleChartCrosshairMove = useCallback((time: Time | null) => {
    if (time === null) {
      setSharedHoverTime(null);
      // 모든 보조지표 크로스헤어 클리어
      volumeChartRef.current?.clearCrosshair?.();
      newPsychologicalChartRef.current?.clearCrosshair?.();
      investPsychologicalChartRef.current?.clearCrosshair?.();
      macdChartRef.current?.clearCrosshair?.();
      cciChartRef.current?.clearCrosshair?.();
      adxChartRef.current?.clearCrosshair?.();
      bwiChartRef.current?.clearCrosshair?.();
      dmiChartRef.current?.clearCrosshair?.();
      obvChartRef.current?.clearCrosshair?.();
      rsiChartRef.current?.clearCrosshair?.();
      stochasticChartRef.current?.clearCrosshair?.();
      williamsRChartRef.current?.clearCrosshair?.();
      trixChartRef.current?.clearCrosshair?.();
      volumeOscChartRef.current?.clearCrosshair?.();
      vrChartRef.current?.clearCrosshair?.();
      disparityChartRef.current?.clearCrosshair?.();
      return;
    }
    const timeStr = typeof time === 'number' ? new Date(time * 1000).toISOString() : time.toString();
    setSharedHoverTime(timeStr);
    
    // 모든 보조지표 크로스헤어 동기화
    try {
      volumeChartRef.current?.setCrosshairPosition?.(time);
      newPsychologicalChartRef.current?.setCrosshairPosition?.(time);
      investPsychologicalChartRef.current?.setCrosshairPosition?.(time);
      macdChartRef.current?.setCrosshairPosition?.(time);
      cciChartRef.current?.setCrosshairPosition?.(time);
      adxChartRef.current?.setCrosshairPosition?.(time);
      bwiChartRef.current?.setCrosshairPosition?.(time);
      dmiChartRef.current?.setCrosshairPosition?.(time);
      obvChartRef.current?.setCrosshairPosition?.(time);
      rsiChartRef.current?.setCrosshairPosition?.(time);
      stochasticChartRef.current?.setCrosshairPosition?.(time);
      williamsRChartRef.current?.setCrosshairPosition?.(time);
      trixChartRef.current?.setCrosshairPosition?.(time);
      volumeOscChartRef.current?.setCrosshairPosition?.(time);
      vrChartRef.current?.setCrosshairPosition?.(time);
      disparityChartRef.current?.setCrosshairPosition?.(time);
    } catch (e) {
      // 일부 차트가 아직 초기화되지 않았을 수 있음
    }
  }, []);

  // ✅ 보조지표 → 캔들차트 및 모든 보조지표 크로스헤어 동기화
  const handleIndicatorCrosshairMove = useCallback((time: Time | null) => {
    if (time === null) {
      setSharedHoverTime(null);
      chartRef.current?.clearCrosshair();
      // 모든 보조지표 크로스헤어 클리어
      volumeChartRef.current?.clearCrosshair?.();
      newPsychologicalChartRef.current?.clearCrosshair?.();
      investPsychologicalChartRef.current?.clearCrosshair?.();
      macdChartRef.current?.clearCrosshair?.();
      cciChartRef.current?.clearCrosshair?.();
      adxChartRef.current?.clearCrosshair?.();
      bwiChartRef.current?.clearCrosshair?.();
      dmiChartRef.current?.clearCrosshair?.();
      obvChartRef.current?.clearCrosshair?.();
      rsiChartRef.current?.clearCrosshair?.();
      stochasticChartRef.current?.clearCrosshair?.();
      williamsRChartRef.current?.clearCrosshair?.();
      trixChartRef.current?.clearCrosshair?.();
      volumeOscChartRef.current?.clearCrosshair?.();
      vrChartRef.current?.clearCrosshair?.();
      disparityChartRef.current?.clearCrosshair?.();
      return;
    }
    const timeStr = typeof time === 'number' ? new Date(time * 1000).toISOString() : time.toString();
    setSharedHoverTime(timeStr);
    
    // 캔들차트의 크로스헤어도 업데이트
    if (chartRef.current) {
      try {
        chartRef.current.setCrosshairPosition(time);
      } catch (e) {
        // setCrosshairPosition이 없을 수 있음
      }
    }
    
    // 모든 보조지표 크로스헤어 동기화
    try {
      volumeChartRef.current?.setCrosshairPosition?.(time);
      newPsychologicalChartRef.current?.setCrosshairPosition?.(time);
      investPsychologicalChartRef.current?.setCrosshairPosition?.(time);
      macdChartRef.current?.setCrosshairPosition?.(time);
      cciChartRef.current?.setCrosshairPosition?.(time);
      adxChartRef.current?.setCrosshairPosition?.(time);
      bwiChartRef.current?.setCrosshairPosition?.(time);
      dmiChartRef.current?.setCrosshairPosition?.(time);
      obvChartRef.current?.setCrosshairPosition?.(time);
      rsiChartRef.current?.setCrosshairPosition?.(time);
      stochasticChartRef.current?.setCrosshairPosition?.(time);
      williamsRChartRef.current?.setCrosshairPosition?.(time);
      trixChartRef.current?.setCrosshairPosition?.(time);
      volumeOscChartRef.current?.setCrosshairPosition?.(time);
      vrChartRef.current?.setCrosshairPosition?.(time);
      disparityChartRef.current?.setCrosshairPosition?.(time);
    } catch (e) {
      // 일부 차트가 아직 초기화되지 않았을 수 있음
    }
  }, []);

  // 상태 변경 시 sessionStorage에 저장
  useEffect(() => {
    try {
    const stateToSave = {
      uptrendStrategy,
      downtrendStrategy,
      symbol,
      timeframe,
      period,
      initialCapital,
      rightPanelTab,
      trendStrategy,
      leftPanelOpen,
      rightPanelOpen,
      periodOffset,
    };
    sessionStorage.setItem(STORAGE_KEY, JSON.stringify(stateToSave));
    } catch (e) {
      console.warn('sessionStorage 저장 실패:', e);
    }
  }, [uptrendStrategy, downtrendStrategy, symbol, timeframe, period, initialCapital, rightPanelTab, trendStrategy, leftPanelOpen, rightPanelOpen, periodOffset]);

  // 데이터 로드
  useEffect(() => {
    loadStrategyRules();
  }, []);
  
  // 전략관리 규칙 목록 로드
  const loadStrategyRules = async () => {
    try {
      const data = await getStrategyRules();
      setStrategyRules(data);
    } catch (err) {
      console.error('전략 규칙 목록 로드 실패:', err);
    }
  };
  
  // 정배열 전략 목록 (UPTREND 또는 ALL)
  const uptrendRules = useMemo(() => 
    strategyRules.filter(r => r.enabled && (r.trendType === 'UPTREND' || r.trendType === 'ALL')),
    [strategyRules]
  );
  
  // 역배열 전략 목록 (DOWNTREND 또는 ALL)
  const downtrendRules = useMemo(() => 
    strategyRules.filter(r => r.enabled && (r.trendType === 'DOWNTREND' || r.trendType === 'ALL')),
    [strategyRules]
  );

  // 종목 변경 핸들러
  const handleCryptoChange = (newSymbol: string) => {
    setSymbol(newSymbol);
    setResult(null);
  };

  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;
    }
  };

  const calculateDateRange = (periodValue: string, offset: number = 0): { startDate: string; endDate: string } => {
    const periodDays = getPeriodDays(periodValue);
    const today = new Date();
    const endDate = new Date(today);
    endDate.setDate(today.getDate() - (periodDays * offset));
    const startDate = new Date(endDate);
    startDate.setDate(endDate.getDate() - periodDays);
    return {
      startDate: startDate.toISOString().split('T')[0] + 'T00:00:00',
      endDate: endDate.toISOString().split('T')[0] + 'T23:59:59',
    };
  };

  const getCurrentPeriodLabel = (): string => {
    const { startDate, endDate } = calculateDateRange(period, periodOffset);
    const start = new Date(startDate);
    const end = new Date(endDate);
    return `${start.getMonth() + 1}/${start.getDate()} ~ ${end.getMonth() + 1}/${end.getDate()}`;
  };

  const canGoPrevious = (): boolean => {
    const periodDays = getPeriodDays(period);
    const maxOffset = Math.floor(365 / periodDays);
    return periodOffset < maxOffset;
  };

  const canGoNext = (): boolean => {
    return periodOffset > 0;
  };

  const convertToMacdResult = (candleData: CandleData[], indicatorData: IndicatorData[], tradeRecords?: TradeRecord[]): MacdResult[] => {
    if (!candleData || candleData.length === 0) return [];
    
    // tradeRecords의 timestamp를 Set으로 만들어 빠른 조회 가능하게 함
    const buyTimestamps = new Set<string>();
    const sellTimestamps = new Set<string>();
    
    if (tradeRecords && tradeRecords.length > 0) {
      tradeRecords.forEach(trade => {
        const ts = trade.timestamp;
        // 다양한 형식으로 타임스탬프 저장
        const variants = [
          ts,
          ts.replace('T', ' '),
          ts.replace(' ', 'T'),
          ts.split('.')[0], // 밀리초 제거
          ts.split('.')[0].replace('T', ' '),
          ts.split('+')[0], // 타임존 제거
        ];
        
        if (trade.tradeType === 'BUY') {
          variants.forEach(v => buyTimestamps.add(v));
        } else if (trade.tradeType === 'SELL') {
          variants.forEach(v => sellTimestamps.add(v));
        }
      });
    }
    
    // candleData의 isBuyPoint/isSellPoint 분석
    const candleBuyPoints = candleData.filter(c => c.isBuyPoint).length;
    const candleSellPoints = candleData.filter(c => c.isSellPoint).length;
    
    // 디버깅 로그
    console.log('📊 백테스트 신호 분석:', { 
      totalCandles: candleData.length,
      indicatorCount: indicatorData.length,
      tradeRecordsProvided: !!tradeRecords,
      totalTradeRecords: tradeRecords?.length || 0,
      candleBuyPoints,
      candleSellPoints,
    });
    
    // isBuyPoint가 true인 캔들 찾기
    const buyPointCandles = candleData.filter(c => c.isBuyPoint);
    if (buyPointCandles.length > 0) {
      // 매수 포인트의 인덱스 찾기
      const buyPointIndices = candleData.map((c, idx) => c.isBuyPoint ? idx : -1).filter(idx => idx !== -1);
      console.log('🟢 매수 포인트 캔들:', buyPointCandles.map(c => ({ time: c.time, isBuyPoint: c.isBuyPoint })));
      console.log('🟢 매수 포인트 인덱스:', buyPointIndices, `(전체 ${candleData.length}개 중)`);
      console.log('🟢 차트 표시 범위: 마지막 120개 = 인덱스 ${candleData.length - 120} ~ ${candleData.length - 1}');
      
      // 매수 포인트가 마지막 120개 범위 내에 있는지 확인
      const visibleRangeStart = Math.max(0, candleData.length - 120);
      const isInVisibleRange = buyPointIndices.some(idx => idx >= visibleRangeStart);
      if (!isInVisibleRange) {
        console.log('⚠️ 매수 포인트가 현재 차트 표시 범위(마지막 120개) 밖에 있습니다!');
      }
    } else {
      console.log('⚠️ isBuyPoint가 true인 캔들이 없습니다!');
      // 첫 5개 캔들의 isBuyPoint 값 확인
      console.log('📋 첫 5개 캔들 샘플:', candleData.slice(0, 5).map(c => ({ time: c.time, isBuyPoint: c.isBuyPoint, isSellPoint: c.isSellPoint })));
    }
    
    const isIntraday = (timeframe.endsWith('m') && timeframe !== '1M') || timeframe.endsWith('h');
    const useIndexMapping = candleData.length === indicatorData.length;
    
    const indicatorMap = new Map<string, IndicatorData>();
    indicatorData.forEach(ind => {
        indicatorMap.set(ind.time, ind);
      if (ind.time.includes('T')) {
        indicatorMap.set(ind.time.replace('T', ' '), ind);
        indicatorMap.set(ind.time.split('T')[0], ind);
      } else if (ind.time.includes(' ')) {
        indicatorMap.set(ind.time.replace(' ', 'T'), ind);
        indicatorMap.set(ind.time.split(' ')[0], ind);
      }
    });

    // 캔들 시간과 tradeRecords 시간 매칭 함수 (유연한 매칭)
    const normalizeTimestamp = (ts: string): string => {
      // 밀리초 제거, T/공백 통일, 타임존 제거
      return ts.replace('T', ' ').split('.')[0].split('+')[0].trim();
    };
    
    const matchesTimestamp = (candleTime: string, timestampSet: Set<string>): boolean => {
      const normalizedCandle = normalizeTimestamp(candleTime);
      const timestamps = Array.from(timestampSet);
      for (let i = 0; i < timestamps.length; i++) {
        const normalizedTs = normalizeTimestamp(timestamps[i]);
        // 정확한 매칭 또는 분 단위까지 매칭 (초 무시)
        if (normalizedCandle === normalizedTs) return true;
        // 분 단위까지만 비교 (초 차이 허용)
        if (normalizedCandle.substring(0, 16) === normalizedTs.substring(0, 16)) return true;
      }
      return false;
    };

    return candleData.map((candle, index) => {
      let indicator: IndicatorData | undefined;
      
      if (useIndexMapping) {
        indicator = indicatorData[index];
      }
      
      if (!indicator) {
        indicator = indicatorMap.get(candle.time);
        if (!indicator && candle.time.includes('T')) {
          indicator = indicatorMap.get(candle.time.replace('T', ' '));
          if (!indicator) indicator = indicatorMap.get(candle.time.split('T')[0]);
        }
        if (!indicator && candle.time.includes(' ')) {
          indicator = indicatorMap.get(candle.time.replace(' ', 'T'));
          if (!indicator) indicator = indicatorMap.get(candle.time.split(' ')[0]);
        }
      }
      
      let displayDate = candle.time;
      if (isIntraday) {
        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];
      }
      
      // candleData의 isBuyPoint/isSellPoint를 우선 사용 (백엔드에서 설정됨)
      // tradeRecords 매칭은 보조적으로 사용
      let signal: 'BUY' | 'SELL' | 'HOLD' = 'HOLD';
      
      // 1순위: candleData의 isBuyPoint/isSellPoint (백엔드에서 직접 설정)
      if (candle.isBuyPoint) {
        signal = 'BUY';
      } else if (candle.isSellPoint) {
        signal = 'SELL';
      } 
      // 2순위: tradeRecords 타임스탬프 매칭 (fallback)
      else if (tradeRecords && tradeRecords.length > 0) {
        const isBuy = matchesTimestamp(candle.time, buyTimestamps);
        const isSell = matchesTimestamp(candle.time, sellTimestamps);
        if (isBuy) {
          signal = 'BUY';
        } else if (isSell) {
          signal = 'SELL';
        }
      }
      
      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,
        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: indicator?.ma10 ?? null,
        sma26: indicator?.ma20 ?? null,
        sma60: indicator?.ma60 ?? null,
        ichimokuTenkan: indicator?.ichimokuTenkan ?? null,
        ichimokuKijun: indicator?.ichimokuKijun ?? null,
        ichimokuChikou: indicator?.ichimokuChikou ?? null,
        ichimokuSenkouA: indicator?.ichimokuSenkouA ?? null,
        ichimokuSenkouB: indicator?.ichimokuSenkouB ?? null,
        trix: indicator?.trix ?? null,
        trixSignal: indicator?.trixSignal ?? null,
      } as MacdResult;
    });
  };

  const executeBacktest = async (periodVal: string, offsetVal: number, timeframeVal: string, isPeriodChange: boolean = false) => {
    if ((!uptrendStrategy && !downtrendStrategy) || !symbol) {
      setError('전략과 종목을 선택해주세요.');
      return;
    }
    
    // ✅ 업비트 방식: 기간 변경은 isPeriodLoading, 초기 로딩은 loading
    if (isPeriodChange) {
      setIsPeriodLoading(true);
    } else {
      setLoading(true);
    }
    setError('');
    
    try {
      const { startDate, endDate } = calculateDateRange(periodVal, offsetVal);
      const indicatorSettings = loadIndicatorSettings();
      
      const request: BacktestRequest = {
        symbol,
        strategyId: 0,
        startDate,
        endDate,
        initialCapital,
        positionSizeRatio: 1.0,
        commissionRate: 0.0005,
        timeframe: timeframeVal,
        // 전략관리 규칙 ID (정배열/역배열 전략)
        uptrendStrategyId: uptrendStrategy ? Number(uptrendStrategy) : undefined,
        downtrendStrategyId: downtrendStrategy ? Number(downtrendStrategy) : undefined,
        // 추세 판단 MA 설정
        trendShortMA: trendShortMA,
        trendMediumMA: trendMediumMA,
        trendLongMA: trendLongMA,
        // 보조지표 설정
        macdFastPeriod: indicatorSettings.macdFastPeriod,
        macdSlowPeriod: indicatorSettings.macdSlowPeriod,
        macdSignalPeriod: indicatorSettings.macdSignalPeriod,
        stochasticKPeriod: indicatorSettings.stochasticKPeriod,
        stochasticDPeriod: indicatorSettings.stochasticDPeriod,
        stochasticSlowing: indicatorSettings.stochasticSlowing,
        williamsRPeriod: indicatorSettings.williamsRPeriod,
        rsiPeriod: indicatorSettings.rsiPeriod,
        rsiOversold: indicatorSettings.rsiOversold,
        rsiOverbought: indicatorSettings.rsiOverbought,
      };

      const backtestResult = await runBacktest(request);
      
      // ✅ 빈 데이터 체크
      if (!backtestResult.candleData || backtestResult.candleData.length === 0) {
        setError('해당 기간에 데이터가 없습니다.');
        // ✅ 기간 변경 시 에러가 나면 이전 result 유지
        return;
      }
      
      setResult(backtestResult);
    } catch (err: any) {
      console.error('백테스팅 실행 실패:', err);
      const errorMessage = err.response?.data?.message || '백테스팅 실행 중 오류가 발생했습니다.';
      setError(errorMessage);
      // ✅ 기간 변경 시 에러가 나도 이전 result 유지
    } finally {
      if (isPeriodChange) {
        setIsPeriodLoading(false);
      } else {
        setLoading(false);
      }
    }
  };

  const handlePreviousPeriod = async () => {
    if (!canGoPrevious() || loading || isPeriodLoading) return;
    const newOffset = periodOffset + 1;
    setPeriodOffset(newOffset);
    // ✅ 업비트 방식: 기간 변경은 isPeriodChange=true로 호출
    await executeBacktest(period, newOffset, timeframe, true);
  };

  const handleNextPeriod = async () => {
    if (!canGoNext() || loading || isPeriodLoading) return;
    const newOffset = periodOffset - 1;
    setPeriodOffset(newOffset);
    // ✅ 업비트 방식: 기간 변경은 isPeriodChange=true로 호출
    await executeBacktest(period, newOffset, timeframe, true);
  };

  const handleRunBacktest = async () => {
    setPeriodOffset(0);
    setResult(null);
    await executeBacktest(period, 0, timeframe, false); // ✅ 초기 실행
    // 모바일에서 실행 후 차트 탭으로 이동
    if (isMobile || isTablet) {
      setMobileSettingsOpen(false);
      setMobileActiveTab('chart');
    }
  };

  // ✅ 시그널 업데이트 함수 (백테스트 재실행 없이 시그널만 갱신)
  // ✅ result를 useRef로 관리하여 무한 루프 방지
  const resultRef = useRef(result);
  useEffect(() => {
    resultRef.current = result;
  }, [result]);

  // ✅ 시그널 분석 진행 중 플래그 (무한 루프 방지)
  const isAnalyzingSignalsRef = useRef(false);

  const updateSignalsWithData = useCallback(async () => {
    // ✅ 이미 분석 중이면 스킵
    if (isAnalyzingSignalsRef.current) {
      console.log('⏸️ [SimulationPage] 시그널 분석 이미 진행 중 - 스킵');
      return;
    }

    const currentResult = resultRef.current;
    if (!currentResult || !symbol) return;
    if (!uptrendStrategy && !downtrendStrategy) {
      console.log('⚠️ [SimulationPage] 전략이 선택되지 않음 - 시그널 분석 건너뜀');
      return;
    }

    isAnalyzingSignalsRef.current = true; // ✅ 분석 시작 플래그
    console.log(`📊 [SimulationPage] 시그널 분석 시작: symbol=${symbol}, interval=${timeframe}`);

    try {
      const indicatorSettings = loadIndicatorSettings();
      
      // BacktestResult의 candleData를 CandleData 형식으로 변환
      const candleData = currentResult.candleData.map(c => ({
        time: c.time,
        open: c.open,
        high: c.high,
        low: c.low,
        close: c.close,
        volume: c.volume,
        isBuyPoint: false,
        isSellPoint: false
      }));

      // indicatorData도 변환
      const indicatorData = currentResult.indicatorData.map(ind => ({
        time: ind.time,
        macdLine: ind.macdLine,
        macdSignal: ind.signalLine,
        macdHistogram: ind.histogram,
        stochasticK: ind.stochK,
        stochasticD: ind.stochD,
        rsi: ind.rsi,
        // ❌ EMA 사용하지 않음 - SMA만 사용
        // ema5: ind.ma10,
        // ema10: ind.ma10,
        // ema20: ind.ma20,
        // ema60: ind.ma60,
        // ema120: ind.ma200,
      }));

      const request: SignalAnalysisRequest = {
        symbol,
        interval: timeframe,
        candleData,
        indicatorData,  // ✅ 이미 계산된 지표 데이터 전송
        uptrendStrategyId: uptrendStrategy ? Number(uptrendStrategy) : undefined,
        downtrendStrategyId: downtrendStrategy ? Number(downtrendStrategy) : undefined,
        trendShortMA: trendShortMA,
        trendMediumMA: trendMediumMA,
        trendLongMA: trendLongMA,
        macdFastPeriod: indicatorSettings.macdFastPeriod,
        macdSlowPeriod: indicatorSettings.macdSlowPeriod,
        macdSignalPeriod: indicatorSettings.macdSignalPeriod,
        stochasticKPeriod: indicatorSettings.stochasticKPeriod,
        stochasticDPeriod: indicatorSettings.stochasticDPeriod,
        stochasticSlowing: indicatorSettings.stochasticSlowing,
        williamsRPeriod: indicatorSettings.williamsRPeriod,
        rsiPeriod: indicatorSettings.rsiPeriod,
        rsiOversold: indicatorSettings.rsiOversold,
        rsiOverbought: indicatorSettings.rsiOverbought,
      };

      const response = await analyzeSignals(request);

      if (response.success && response.signals) {
        console.log(`✅ [SimulationPage] 시그널 분석 완료: 매수 ${response.buySignalCount}개, 매도 ${response.sellSignalCount}개`);

        // ✅ 시그널 맵 생성 (중복 방지)
        const signalMap = new Map<string, CandleSignal>();
        response.signals.forEach(signal => {
          if (signalMap.has(signal.time)) {
            console.warn(`⚠️ [SimulationPage] 중복 시그널 감지 (무시됨): ${signal.time}`);
            return;
          }
          if (signal.isBuyPoint && signal.isSellPoint) {
            console.error(`❌ [SimulationPage] 시그널 충돌: ${signal.time}에 BUY와 SELL 동시 발생 (무시됨)`);
            return;
          }
          signalMap.set(signal.time, signal);
        });

        // ✅ candleData에 시그널 정확히 반영
        const candleDataWithSignals = currentResult.candleData.map(c => {
          const signal = signalMap.get(c.time);
          return {
            ...c,
            isBuyPoint: signal?.isBuyPoint || false,
            isSellPoint: signal?.isSellPoint || false
          };
        });

        // ✅ 백테스트 결과 업데이트 (candleData만 변경, 나머지는 유지)
        setResult(prev => prev ? {
          ...prev,
          candleData: candleDataWithSignals
        } : null);

        console.log(`✅ [SimulationPage] 시그널 적용 완료`);
      }
    } catch (error) {
      console.error('❌ [SimulationPage] 시그널 분석 실패:', error);
    } finally {
      isAnalyzingSignalsRef.current = false; // ✅ 분석 완료 플래그
    }
  }, [symbol, timeframe, uptrendStrategy, downtrendStrategy, trendShortMA, trendMediumMA, trendLongMA]);

  // ✅ updateSignalsWithData의 최신 버전을 ref에 저장
  const updateSignalsWithDataRef = useRef(updateSignalsWithData);
  useEffect(() => {
    updateSignalsWithDataRef.current = updateSignalsWithData;
  }, [updateSignalsWithData]);

  // ✅ 전략 변경 시 시그널 자동 갱신 (무한 루프 방지)
  useEffect(() => {
    const currentResult = resultRef.current;
    if (currentResult && currentResult.candleData.length > 0) {
      if (uptrendStrategy || downtrendStrategy) {
        console.log(`🔄 [SimulationPage] 전략 변경 감지 - 시그널 자동 갱신: uptrend=${uptrendStrategy}, downtrend=${downtrendStrategy}`);
        // ✅ ref를 통해 최신 함수 호출
        updateSignalsWithDataRef.current();
      } else {
        // 전략이 없으면 시그널 초기화
        console.log('🔄 [SimulationPage] 전략 없음 - 시그널 초기화');
        setResult(prev => prev ? {
          ...prev,
          candleData: prev.candleData.map(c => ({
            ...c,
            isBuyPoint: false,
            isSellPoint: false
          }))
        } : null);
      }
    }
  }, [uptrendStrategy, downtrendStrategy]); // ✅ updateSignalsWithData 제거

  // ✅ 1분마다 자동 갱신 (현재 기간을 보고 있을 때만: periodOffset === 0)
  useEffect(() => {
    if (periodOffset !== 0) {
      console.log('⏸️ [SimulationPage] 과거 기간 조회 중 - 자동 갱신 비활성화');
      return;
    }

    const currentResult = resultRef.current;
    if (!currentResult || !symbol || (!uptrendStrategy && !downtrendStrategy)) {
      console.log('⏸️ [SimulationPage] 백테스트 미실행 또는 전략 미선택 - 자동 갱신 비활성화');
      return;
    }

    console.log('⏰ [SimulationPage] 1분 자동 갱신 타이머 시작 (현재 기간)');
    const intervalId = setInterval(() => {
      console.log('🔄 [SimulationPage] 1분 경과 - 백테스트 자동 재실행');
      executeBacktest(period, 0, timeframe, false); // ✅ 자동 갱신은 초기 실행 취급
    }, 60000); // 60초 = 1분

    return () => {
      console.log('⏰ [SimulationPage] 1분 자동 갱신 타이머 정리');
      clearInterval(intervalId);
    };
  }, [periodOffset, symbol, uptrendStrategy, downtrendStrategy, period, timeframe, executeBacktest]);

  // ✅ 에러 메시지 자동 제거 (3초 후)
  useEffect(() => {
    if (!error) return;
    
    const timer = setTimeout(() => {
      setError('');
    }, 3000);
    
    return () => clearTimeout(timer);
  }, [error]);

  const handleIntervalChange = async (newInterval: string) => {
    if (!newInterval || newInterval === timeframe) return;
    setTimeframe(newInterval);
    if (result) {
      await executeBacktest(period, periodOffset, newInterval, true); // ✅ 시간봉 변경은 기간 변경
    }
  };

  const handlePeriodChange = async (newPeriod: string) => {
    if (!newPeriod || newPeriod === period) return;
    setPeriod(newPeriod);
    setPeriodOffset(0);
    if (result) {
      await executeBacktest(newPeriod, 0, timeframe, true); // ✅ 기간 변경
    }
  };

  // 기본 계산 값 (나중에 filteredPerformance로 대체됨)
  const currentPrice = result?.candleData?.[result.candleData.length - 1]?.close || 0;
  const priceChange = result ? result.returnRate : 0;

  // ✅ CandleData with trade markers (CandlestickChart 호환)
  const chartData = useMemo(() => {
    if (!result?.candleData) return [];
    
    // tradeRecords를 사용하여 매수/매도 포인트 표시
    const candleDataWithMarkers = result.candleData.map(candle => {
      const tradeAtThisTime = result.tradeRecords?.find(trade => {
        // 시간 매칭 (T와 공백 변환 고려)
        const candleTime = candle.time.replace('T', ' ').replace('Z', '');
        const tradeTime = trade.timestamp?.replace('T', ' ').replace('Z', '');
        return candleTime === tradeTime;
      });
      
      return {
        ...candle,
        isBuyPoint: tradeAtThisTime?.tradeType === 'BUY',
        isSellPoint: tradeAtThisTime?.tradeType === 'SELL',
      };
    });
    
    return candleDataWithMarkers;
  }, [result?.candleData, result?.tradeRecords]);

  // 거래내역 (전체 거래내역 표시 - 차트 범위 필터링 제거)
  const filteredTradeRecords = useMemo(() => {
    if (!result?.tradeRecords || result.tradeRecords.length === 0) return [];
    
    // 전체 거래내역 반환 (차트 범위와 무관하게 모든 거래 표시)
    console.log('📋 거래내역:', result.tradeRecords.length, '건');
    return result.tradeRecords;
  }, [result?.tradeRecords]);

  // 차트 표시 기간 내의 성과 계산 (filteredTradeRecords 기반)
  const filteredPerformance = useMemo(() => {
    if (!filteredTradeRecords || filteredTradeRecords.length === 0) {
      return {
        returnRate: 0,
        netProfit: 0,
        totalTrades: 0,
        buyCount: 0,
        sellCount: 0,
        winRate: 0,
        maxDrawdown: 0,
        winningTrades: 0,
        losingTrades: 0,
      };
    }
    
    const initialCapital = result?.initialCapital || 10000000;
    const buyTrades = filteredTradeRecords.filter(t => t.tradeType === 'BUY');
    const sellTrades = filteredTradeRecords.filter(t => t.tradeType === 'SELL');
    
    // 수익/손실 계산: 매도 거래의 수익률 합산
    let totalProfitLoss = 0;
    let winningCount = 0;
    let losingCount = 0;
    let maxDrawdown = 0;
    let peakCapital = initialCapital;
    let currentCapital = initialCapital;
    
    // 매수-매도 쌍으로 수익 계산
    const pairedTrades: { buy: typeof filteredTradeRecords[0], sell: typeof filteredTradeRecords[0] }[] = [];
    let pendingBuy: typeof filteredTradeRecords[0] | null = null;
    
    filteredTradeRecords.forEach(trade => {
      if (trade.tradeType === 'BUY') {
        pendingBuy = trade;
      } else if (trade.tradeType === 'SELL' && pendingBuy) {
        pairedTrades.push({ buy: pendingBuy, sell: trade });
        pendingBuy = null;
      }
    });
    
    // 각 거래 쌍의 수익률 계산
    pairedTrades.forEach(pair => {
      const buyPrice = pair.buy.price;
      const sellPrice = pair.sell.price;
      const tradeReturn = ((sellPrice - buyPrice) / buyPrice) * 100;
      const tradeProfitLoss = (sellPrice - buyPrice) * (pair.buy.quantity || 1);
      
      totalProfitLoss += tradeProfitLoss;
      currentCapital += tradeProfitLoss;
      
      if (tradeReturn > 0) {
        winningCount++;
      } else {
        losingCount++;
      }
      
      // 최대 자산 갱신
      if (currentCapital > peakCapital) {
        peakCapital = currentCapital;
      }
      
      // 낙폭 계산
      const drawdown = peakCapital > 0 ? ((peakCapital - currentCapital) / peakCapital) * 100 : 0;
      if (drawdown > maxDrawdown) {
        maxDrawdown = drawdown;
      }
    });
    
    const returnRate = initialCapital > 0 ? (totalProfitLoss / initialCapital) * 100 : 0;
    const winRate = pairedTrades.length > 0 ? (winningCount / pairedTrades.length) * 100 : 0;
    
    return {
      returnRate,
      netProfit: totalProfitLoss,
      totalTrades: filteredTradeRecords.length,
      buyCount: buyTrades.length,
      sellCount: sellTrades.length,
      winRate,
      maxDrawdown,
      winningTrades: winningCount,
      losingTrades: losingCount,
      finalCapital: initialCapital + totalProfitLoss,
    };
  }, [filteredTradeRecords, result?.initialCapital]);

  // 차트 표시 기간 내 성과 값 (filteredPerformance 기반)
  const displayReturnRate = filteredPerformance?.returnRate ?? (result?.returnRate || 0);
  const displayNetProfit = filteredPerformance?.netProfit ?? (result?.netProfit || 0);
  const displayTotalTrades = filteredPerformance?.totalTrades ?? (result?.totalTrades || 0);
  const displayWinRate = filteredPerformance?.winRate ?? (result?.winRate || 0);
  const displayMaxDrawdown = filteredPerformance?.maxDrawdown ?? (result?.maxDrawdown || 0);
  const displayFinalCapital = filteredPerformance?.finalCapital ?? (result?.finalCapital || 0);
  const displayBuyCount = filteredPerformance?.buyCount ?? (result?.buyCount || 0);
  const displaySellCount = filteredPerformance?.sellCount ?? (result?.sellCount || 0);
  const returnRate = displayReturnRate;
  const netProfit = displayNetProfit;
  const isProfit = returnRate >= 0;

  const calculateAccuracy = () => {
    if (!filteredTradeRecords || filteredTradeRecords.length === 0) {
      return { overall: 0, buy: 0, sell: 0 };
    }
    const sellTrades = filteredTradeRecords.filter(t => t.tradeType === 'SELL');
    const winningTrades = sellTrades.filter(t => (t.returnRate || 0) > 0).length;
    const overall = sellTrades.length > 0 ? (winningTrades / sellTrades.length) * 100 : 0;
    return { overall, buy: overall, sell: overall };
  };

  const accuracy = calculateAccuracy();

  // ========== 공통 JSX 요소 ==========
  
  // 설정 패널 컨텐츠
  const settingsContent = (
    <Box sx={{ p: 2 }}>
      <Box sx={{ mb: 2 }}>
        <Typography sx={{ fontSize: '11px', color: themeStyle.textSecondaryColor, mb: 0.75 }}>
          투자 종목
        </Typography>
          <CryptoNameComboBox
            value={symbol}
            onChange={handleCryptoChange}
            disabled={loading}
            label=""
            placeholder="종목 선택"
            size="small"
          />
        </Box>
          
          {/* 정배열 전략 */}
          <Box sx={{ mb: 2 }}>
            <Typography sx={{ fontSize: '11px', color: themeStyle.textSecondaryColor, mb: 0.75, display: 'flex', alignItems: 'center', gap: 0.5 }}>
              <TrendingUp sx={{ fontSize: 14, color: '#22c55e' }} />
              정배열 전략
            </Typography>
            <FormControl fullWidth size="small">
              <Select
                value={uptrendStrategy}
                onChange={(e) => setUptrendStrategy(e.target.value as number | '')}
                sx={{ bgcolor: themeStyle.backgroundColor, fontSize: '13px' }}
                displayEmpty
              >
                <MenuItem value="">선택안함</MenuItem>
                {uptrendRules.map((r) => (
                  <MenuItem key={r.id} value={r.id}>{r.name}</MenuItem>
                ))}
              </Select>
            </FormControl>
          </Box>
          
          {/* 역배열 전략 */}
          <Box sx={{ mb: 2 }}>
            <Typography sx={{ fontSize: '11px', color: themeStyle.textSecondaryColor, mb: 0.75, display: 'flex', alignItems: 'center', gap: 0.5 }}>
              <TrendingDown sx={{ fontSize: 14, color: '#ef4444' }} />
              역배열 전략
            </Typography>
            <FormControl fullWidth size="small">
              <Select
                value={downtrendStrategy}
                onChange={(e) => setDowntrendStrategy(e.target.value as number | '')}
                sx={{ bgcolor: themeStyle.backgroundColor, fontSize: '13px' }}
                displayEmpty
              >
                <MenuItem value="">선택안함</MenuItem>
                {downtrendRules.map((r) => (
                  <MenuItem key={r.id} value={r.id}>{r.name}</MenuItem>
                ))}
              </Select>
            </FormControl>
          </Box>
          
          {/* 추세 판단 전략 설정 */}
          <Box sx={{ mb: 2 }}>
            <Typography sx={{ fontSize: '11px', color: themeStyle.textSecondaryColor, mb: 0.75 }}>
              추세 전략
            </Typography>
            <FormControl fullWidth size="small">
              <Select
                value={trendStrategy}
                onChange={(e) => setTrendStrategy(e.target.value as TrendStrategy)}
                sx={{ bgcolor: themeStyle.backgroundColor, fontSize: '13px' }}
              >
                <MenuItem value="aggressive">공격적 전략 (MA5 &gt; MA10 &gt; MA20)</MenuItem>
                <MenuItem value="balanced">균형 전략 (MA10 &gt; MA20 &gt; MA60)</MenuItem>
                <MenuItem value="conservative">보수적 전략 (MA20 &gt; MA60 &gt; MA120)</MenuItem>
              </Select>
            </FormControl>
          </Box>
          
          <Box sx={{ mb: 2 }}>
        <Typography sx={{ fontSize: '11px', color: themeStyle.textSecondaryColor, mb: 0.75 }}>
          분석 기간
        </Typography>
            <FormControl fullWidth size="small">
              <Select
                value={period}
                onChange={(e) => handlePeriodChange(e.target.value)}
            sx={{ bgcolor: themeStyle.backgroundColor, fontSize: '13px' }}
              >
                <MenuItem value="1day">1일</MenuItem>
                <MenuItem value="1week">1주일</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>
          </Box>
          
          <Box sx={{ mb: 2 }}>
        <Typography sx={{ fontSize: '11px', color: isDark ? '#71717a' : '#888', mb: 0.75 }}>
          초기 투자금
        </Typography>
            <TextField
              fullWidth
              size="small"
              type="number"
              value={initialCapital}
              onChange={(e) => setInitialCapital(Number(e.target.value))}
              InputProps={{
                startAdornment: <InputAdornment position="start">₩</InputAdornment>,
              }}
              sx={{ 
                '& .MuiOutlinedInput-root': { 
                  bgcolor: themeStyle.backgroundColor, 
                  fontSize: '13px' 
                } 
              }}
            />
          </Box>
          
          <Button
            fullWidth
            variant="contained"
            onClick={handleRunBacktest}
            disabled={loading || (!uptrendStrategy && !downtrendStrategy)}
            startIcon={loading ? <CircularProgress size={18} /> : <PlayArrow />}
            sx={{
              py: 1.5,
              background: 'linear-gradient(135deg, #22c55e 0%, #16a34a 100%)',
              fontWeight: 600,
              '&:hover': { filter: 'brightness(1.1)' },
              '&:disabled': { background: isDark ? '#27272a' : '#e0e0e0' },
            }}
          >
            {loading ? '실행 중...' : '투자실행'}
          </Button>
        </Box>
  );

  // 결과 패널 컨텐츠
  const resultsContent = (
    <Box>
      <Tabs 
        value={rightPanelTab} 
        onChange={(_, newValue) => setRightPanelTab(newValue)}
          sx={{ 
          minHeight: 42,
          borderBottom: `1px solid ${isDark ? '#27272a' : '#e0e0e0'}`,
          '& .MuiTab-root': {
            minHeight: 42,
            fontSize: '13px',
            fontWeight: 600,
            color: isDark ? '#71717a' : '#888',
            '&.Mui-selected': { color: themeStyle.primaryColor },
          },
          '& .MuiTabs-indicator': { backgroundColor: themeStyle.primaryColor },
        }}
      >
        <Tab label="📊 성과" />
        <Tab label="📋 거래" />
      </Tabs>

      <Box sx={{ p: 2, overflow: 'auto' }}>
        {rightPanelTab === 0 && (
          <>
            <Box sx={{ 
              textAlign: 'center',
              p: 2,
              borderRadius: 2,
              mb: 2,
              bgcolor: isProfit 
                ? (isDark ? 'rgba(34, 197, 94, 0.1)' : 'rgba(34, 197, 94, 0.1)')
                : (isDark ? 'rgba(239, 68, 68, 0.1)' : 'rgba(239, 68, 68, 0.1)'),
              border: `1px solid ${isProfit ? 'rgba(34, 197, 94, 0.2)' : 'rgba(239, 68, 68, 0.2)'}`,
            }}>
              <Typography sx={{ fontSize: '12px', color: isDark ? '#71717a' : '#888', mb: 0.5 }}>
                총 수익률
              </Typography>
              <Typography sx={{ fontSize: '32px', fontWeight: 700, color: isProfit ? '#22c55e' : '#ef4444' }}>
                {isProfit ? '+' : ''}{returnRate.toFixed(2)}%
              </Typography>
              <Typography sx={{ fontSize: '14px', color: isProfit ? '#22c55e' : '#ef4444' }}>
                ₩{Math.round(Math.abs(netProfit)).toLocaleString()}원 {isProfit ? '수익' : '손실'}
              </Typography>
        </Box>

            {/* 최종 자산 - 전체 라인 */}
            <Box sx={{ bgcolor: isDark ? '#1f1f26' : '#f5f5f5', p: 1.5, borderRadius: 1, mb: 1.5 }}>
              <Typography sx={{ fontSize: '11px', color: isDark ? '#71717a' : '#888', mb: 0.5 }}>
                최종 자산
              </Typography>
              <Typography sx={{ fontSize: '20px', fontWeight: 600, color: isDark ? '#fafafa' : '#222' }}>
                ₩{Math.round(displayFinalCapital || initialCapital).toLocaleString()}원
              </Typography>
            </Box>

            {/* 승률, 총 거래, 최대 낙폭 - 그리드 */}
            <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 1.5 }}>
              {[
                { label: '승률', value: `${displayWinRate.toFixed(1)}%`, color: '#22c55e' },
                { label: '총 거래', value: `${displayTotalTrades}회` },
                { label: '최대 낙폭', value: `${displayMaxDrawdown.toFixed(1)}%`, color: '#ef4444' },
              ].map((item, i) => (
                <Box key={i} sx={{ bgcolor: isDark ? '#1f1f26' : '#f5f5f5', p: 1.5, borderRadius: 1 }}>
                  <Typography sx={{ fontSize: '11px', color: isDark ? '#71717a' : '#888', mb: 0.5 }}>
                    {item.label}
                  </Typography>
                  <Typography sx={{ fontSize: '16px', fontWeight: 600, color: item.color }}>
                    {item.value}
                  </Typography>
                </Box>
              ))}
            </Box>
          </>
        )}

        {rightPanelTab === 1 && (
          <Box>
            {/* 거래내역 헤더 */}
            {filteredTradeRecords.length > 0 && (
              <Box sx={{ 
                display: 'flex', 
                justifyContent: 'space-between', 
                alignItems: 'center',
                mb: 1.5,
                pb: 1,
                borderBottom: `1px solid ${isDark ? '#27272a' : '#e0e0e0'}`,
              }}>
                <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666' }}>
                  총 {filteredTradeRecords.length}건의 거래
                </Typography>
                <Chip 
                  label={`매수 ${filteredTradeRecords.filter(t => t.tradeType === 'BUY').length} / 매도 ${filteredTradeRecords.filter(t => t.tradeType === 'SELL').length}`}
                  size="small"
          sx={{ 
                    fontSize: '10px',
                    bgcolor: isDark ? '#27272a' : '#f0f0f0',
                    color: isDark ? '#a1a1aa' : '#666',
                  }}
                />
        </Box>
            )}
            {filteredTradeRecords.map((trade, index) => (
              <Tooltip key={index} title="클릭하여 상세 정보 보기" arrow placement="left">
              <Box 
                onClick={() => handleTradeDoubleClick(trade)}
                sx={{ 
                display: 'flex', 
                alignItems: 'center', 
                p: 1.5, 
                bgcolor: isDark ? '#1f1f26' : '#f5f5f5', 
                borderRadius: 1, 
                mb: 0.75, 
                gap: 1.5,
                cursor: 'pointer',
                '&:hover': {
                  bgcolor: isDark ? '#27272e' : '#eaeaea',
                },
              }}>
                <Box sx={{ 
                  width: 32, 
                  height: 32, 
                  borderRadius: 1,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  bgcolor: trade.tradeType === 'BUY' ? 'rgba(34, 197, 94, 0.2)' : 'rgba(239, 68, 68, 0.2)',
                  color: trade.tradeType === 'BUY' ? '#22c55e' : '#ef4444',
                  fontSize: '12px',
                  fontWeight: 700,
                }}>
                  {trade.tradeType === 'BUY' ? 'B' : 'S'}
                </Box>
                <Box sx={{ flex: 1 }}>
                  <Typography sx={{ fontSize: '12px', fontWeight: 500 }}>
                    {trade.tradeType === 'BUY' ? '매수' : '매도'}
                  </Typography>
                  <Typography sx={{ fontSize: '10px', color: isDark ? '#52525b' : '#999' }}>
                    {new Date(trade.timestamp).toLocaleString('ko-KR', { 
                      month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' 
                    })}
                  </Typography>
                </Box>
                <Box sx={{ textAlign: 'right' }}>
                  <Typography sx={{ fontSize: '12px' }}>₩{(trade.price ?? 0).toLocaleString()}</Typography>
                  <Typography sx={{ 
                    fontSize: '11px', 
                    fontWeight: 600,
                    color: trade.returnRate && trade.returnRate >= 0 ? '#22c55e' : '#ef4444'
                  }}>
                    {trade.returnRate ? `${trade.returnRate >= 0 ? '+' : ''}${trade.returnRate.toFixed(1)}%` : '-'}
                  </Typography>
                </Box>
              </Box>
              </Tooltip>
            ))}
            {filteredTradeRecords.length === 0 && (
              <Box sx={{ textAlign: 'center', py: 4 }}>
                <Typography sx={{ fontSize: '32px', mb: 1 }}>📋</Typography>
                <Typography sx={{ fontSize: '13px', color: isDark ? '#52525b' : '#999', mb: 1 }}>
                  {result ? '해당 기간에 거래가 발생하지 않았습니다' : '거래 내역이 없습니다'}
                </Typography>
                {!result && (
                  <Typography sx={{ fontSize: '11px', color: isDark ? '#3f3f46' : '#bbb' }}>
                    전략을 선택하고 투자실행 버튼을 클릭하세요
                  </Typography>
                )}
              </Box>
            )}
          </Box>
        )}
      </Box>
    </Box>
  );

  // 차트 헤더 생성 함수
  const renderChartHeader = (compact = false) => (
    <Box sx={{ 
      display: 'flex', 
      flexWrap: 'wrap',
      justifyContent: 'space-between', 
      alignItems: 'center', 
      p: compact ? 1 : 1.5,
      gap: 1,
      borderBottom: `1px solid ${isDark ? '#27272a' : '#e0e0e0'}`,
      bgcolor: themeStyle.surfaceColor,
    }}>
      {/* 왼쪽 영역: 심볼 정보 + 기간 이동 + 시간봉 */}
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, flexWrap: 'wrap' }}>
        {/* 심볼 및 가격 */}
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Typography sx={{ fontSize: compact ? '14px' : '18px', fontWeight: 700 }}>
            {symbol.replace('KRW-', '')}/KRW
          </Typography>
          <Typography sx={{ fontSize: compact ? '18px' : '24px', fontWeight: 700, color: isProfit ? '#22c55e' : '#ef4444' }}>
            ₩{currentPrice.toLocaleString()}
          </Typography>
          <Typography sx={{ fontSize: compact ? '12px' : '14px', color: priceChange >= 0 ? '#22c55e' : '#ef4444' }}>
            {priceChange >= 0 ? '+' : ''}{priceChange.toFixed(2)}%
          </Typography>
        </Box>

        {/* 기간 이동 */}
        <Box sx={{ 
          display: 'flex', 
          alignItems: 'center',
          bgcolor: isDark ? '#1f1f26' : '#f0f0f0', 
          p: 0.25,
          px: 0.5,
          borderRadius: 1,
        }}>
          <IconButton
            size="small"
            onClick={handlePreviousPeriod}
            disabled={loading || isPeriodLoading || !canGoPrevious()}
            sx={{ p: 0.25 }}
          >
            <ChevronLeft fontSize="small" />
          </IconButton>
          <Typography sx={{ fontSize: '11px', mx: 0.5, minWidth: '70px', textAlign: 'center' }}>
            {getCurrentPeriodLabel()}
          </Typography>
          <IconButton
            size="small"
            onClick={handleNextPeriod}
            disabled={loading || isPeriodLoading || !canGoNext()}
            sx={{ p: 0.25 }}
          >
            <ChevronRight fontSize="small" />
          </IconButton>
        </Box>
          
        {/* 시간봉 선택 */}
        <FormControl size="small" sx={{ minWidth: 70 }}>
          <Select
            value={timeframe}
            onChange={(e) => handleIntervalChange(e.target.value)}
            sx={{ 
              bgcolor: isDark ? '#1f1f26' : '#f0f0f0', 
              fontSize: '12px',
              '& .MuiSelect-select': { py: 0.5 },
            }}
          >
            <MenuItem value="1m">1분</MenuItem>
            <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">1일</MenuItem>
          </Select>
        </FormControl>
      </Box>

      {/* 오른쪽 영역: 빈 공간 (다른 버튼들은 별도 영역에서 처리) */}
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
      </Box>
    </Box>
  );

  // 차트 영역 생성 함수 (업비트 방식)
  const renderChartArea = (minHeight = '500px') => (
    <Box sx={{ flex: 1, p: isMobile ? 1 : 2, minHeight, position: 'relative' }}>
          {/* 초기 로딩 중 (결과 없을 때만) */}
          {loading && !result && (
            <Box sx={{ 
              display: 'flex', 
              alignItems: 'center', 
              justifyContent: 'center', 
              height: '100%'
            }}>
              <CircularProgress />
            </Box>
          )}
          
          {/* 기간 변경 로딩 인디케이터 (우측 상단, 작게 표시) */}
          {isPeriodLoading && result && (
            <Box sx={{ 
              position: 'absolute',
              top: 16,
              right: 16,
              display: 'flex',
              alignItems: 'center',
              gap: 1,
              bgcolor: isDark ? 'rgba(0,0,0,0.8)' : 'rgba(255,255,255,0.9)',
              px: 2,
              py: 1,
              borderRadius: 2,
              boxShadow: 3,
              zIndex: 10
            }}>
              <CircularProgress size={20} />
              <Typography sx={{ fontSize: '13px', color: isDark ? '#fff' : '#333' }}>
                데이터 로딩 중...
              </Typography>
            </Box>
          )}
          
          {/* 에러 토스트 (차트 위에 오버레이) */}
          {error && result && (
            <Box sx={{ 
              position: 'absolute',
              top: 16,
              left: '50%',
              transform: 'translateX(-50%)',
              bgcolor: '#ef4444',
              color: 'white',
              px: 3,
              py: 1.5,
              borderRadius: 2,
              boxShadow: 3,
              zIndex: 20
            }}>
              <Typography sx={{ fontSize: '14px' }}>{error}</Typography>
            </Box>
          )}
          
          {/* 차트 표시 (result가 있으면 항상 표시) */}
          {result && chartData.length > 0 && (
            <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column', gap: 0 }}>
              {/* 캔들스틱 차트 */}
              <Box sx={{ flexGrow: 1, minHeight: 400 }}>
                <CandlestickChart
                  ref={chartRef}
                  data={chartData}
                  indicatorData={result.indicatorData || []}
                  height={400}
                  onCrosshairMove={handleCandleChartCrosshairMove}
                  externalHoverTime={sharedHoverTime}
                  hideNativeCrosshair={true}
                  showTooltip={true}
                  onMarkerClick={(timestamp, tradeType) => handleMarkerClick(timestamp, tradeType as 'BUY' | 'SELL')}
                />
              </Box>
              
              {/* 거래량 차트 */}
              {indicatorVisibility.settings.volume && (
                <Box sx={{ height: 120 }}>
                  <IndicatorChart
                    ref={volumeChartRef}
                    type="volume"
                    data={result.indicatorData || []}
                    height={120}
                    title="거래량"
                    onCrosshairMove={handleIndicatorCrosshairMove}
                    externalHoverTime={sharedHoverTime}
                    hideNativeCrosshair={true}
                  />
                </Box>
              )}
              
              {/* MACD 차트 */}
              {indicatorVisibility.settings.macdLine && (
                <Box sx={{ height: 150 }}>
                  <IndicatorChart
                    ref={macdChartRef}
                    type="macd"
                    data={result.indicatorData || []}
                    height={150}
                    title="MACD"
                    onCrosshairMove={handleIndicatorCrosshairMove}
                    externalHoverTime={sharedHoverTime}
                    hideNativeCrosshair={true}
                  />
                </Box>
              )}
              
              {/* RSI 차트 */}
              {indicatorVisibility.settings.rsi && (
                <Box sx={{ height: 150 }}>
                  <IndicatorChart
                    ref={rsiChartRef}
                    type="rsi"
                    data={result.indicatorData || []}
                    height={150}
                    title="RSI"
                    onCrosshairMove={handleIndicatorCrosshairMove}
                    externalHoverTime={sharedHoverTime}
                    hideNativeCrosshair={true}
                  />
                </Box>
              )}
              
              {/* Stochastic 차트 */}
              {indicatorVisibility.settings.stochasticSlow && (
                <Box sx={{ height: 150 }}>
                  <IndicatorChart
                    ref={stochasticChartRef}
                    type="stochastic"
                    data={result.indicatorData || []}
                    height={150}
                    title="Stochastic Slow"
                    onCrosshairMove={handleIndicatorCrosshairMove}
                    externalHoverTime={sharedHoverTime}
                    hideNativeCrosshair={true}
                  />
                </Box>
              )}
            </Box>
          )}
          
          {/* 초기 상태 - 결과 없음 */}
          {!loading && !result && (
            <Box sx={{ 
              display: 'flex', 
              alignItems: 'center', 
              justifyContent: 'center', 
              height: '100%',
              flexDirection: 'column',
              gap: 2,
              color: isDark ? '#71717a' : '#888'
            }}>
              {error ? (
                <>
                  <Typography variant="h6" sx={{ color: '#ef4444' }}>⚠️ 오류 발생</Typography>
                  <Typography variant="body2">{error}</Typography>
                </>
              ) : (
                <>
                  <Typography variant="h6">투자를 실행해 주세요</Typography>
                  <Typography variant="body2">
                    {isMobile ? '상단 설정 버튼을 눌러 설정하세요' : '좌측에서 종목과 전략을 선택한 후 실행 버튼을 클릭하세요'}
                  </Typography>
                </>
              )}
            </Box>
          )}
        </Box>
  );

  // ========== 드래그 가능한 모달리스 팝업 (업비트 스타일) ==========
  
  // 드래그 상태를 컴포넌트 레벨에서 관리
  const [perfDragging, setPerfDragging] = useState(false);
  const [tradeDragging, setTradeDragging] = useState(false);
  const perfDragStart = useRef({ x: 0, y: 0, posX: 0, posY: 0 });
  const tradeDragStart = useRef({ x: 0, y: 0, posX: 0, posY: 0 });

  // 성과 팝업 드래그 이벤트
  useEffect(() => {
    if (!perfDragging) return;
    
    const onMove = (e: MouseEvent) => {
      const dx = e.clientX - perfDragStart.current.x;
      const dy = e.clientY - perfDragStart.current.y;
      setPerformancePopupPos({
        x: perfDragStart.current.posX + dx,
        y: perfDragStart.current.posY + dy,
      });
    };
    
    const onUp = () => setPerfDragging(false);
    
    document.addEventListener('mousemove', onMove);
    document.addEventListener('mouseup', onUp);
    
    return () => {
      document.removeEventListener('mousemove', onMove);
      document.removeEventListener('mouseup', onUp);
    };
  }, [perfDragging]);

  // 거래내역 팝업 드래그 이벤트
  useEffect(() => {
    if (!tradeDragging) return;
    
    const onMove = (e: MouseEvent) => {
      const dx = e.clientX - tradeDragStart.current.x;
      const dy = e.clientY - tradeDragStart.current.y;
      setTradeHistoryPopupPos({
        x: tradeDragStart.current.posX + dx,
        y: tradeDragStart.current.posY + dy,
      });
    };
    
    const onUp = () => setTradeDragging(false);
    
    document.addEventListener('mousemove', onMove);
    document.addEventListener('mouseup', onUp);
    
    return () => {
      document.removeEventListener('mousemove', onMove);
      document.removeEventListener('mouseup', onUp);
    };
  }, [tradeDragging]);

  // 투자성과 팝업 리사이즈 이벤트
  useEffect(() => {
    if (!perfResizing) return;
    
    const onMove = (e: MouseEvent) => {
      const deltaX = e.clientX - perfResizeStart.current.x;
      const deltaY = e.clientY - perfResizeStart.current.y;
      setPerformancePopupSize({
        width: Math.max(300, Math.min(600, perfResizeStart.current.width + deltaX)),
        height: Math.max(300, Math.min(800, perfResizeStart.current.height + deltaY)),
      });
    };
    
    const onUp = () => setPerfResizing(false);
    
    document.addEventListener('mousemove', onMove);
    document.addEventListener('mouseup', onUp);
    
    return () => {
      document.removeEventListener('mousemove', onMove);
      document.removeEventListener('mouseup', onUp);
    };
  }, [perfResizing]);

  // 거래내역 팝업 리사이즈 이벤트
  useEffect(() => {
    if (!tradeResizing) return;
    
    const onMove = (e: MouseEvent) => {
      const deltaX = e.clientX - tradeResizeStart.current.x;
      const deltaY = e.clientY - tradeResizeStart.current.y;
      setTradeHistoryPopupSize({
        width: Math.max(320, Math.min(700, tradeResizeStart.current.width + deltaX)),
        height: Math.max(300, Math.min(800, tradeResizeStart.current.height + deltaY)),
      });
    };
    
    const onUp = () => setTradeResizing(false);
    
    document.addEventListener('mousemove', onMove);
    document.addEventListener('mouseup', onUp);
    
    return () => {
      document.removeEventListener('mousemove', onMove);
      document.removeEventListener('mouseup', onUp);
    };
  }, [tradeResizing]);

  // 팝업 렌더링 함수
  const renderPopup = (
    isOpen: boolean,
    onClose: () => void,
    title: string,
    icon: string,
    position: { x: number; y: number },
    opacity: number,
    onOpacityChange: (v: number) => void,
    onDragStart: (e: React.MouseEvent) => void,
    children: React.ReactNode,
    size: { width: number; height: number },
    onResizeStart: (e: React.MouseEvent) => void
  ) => {
    if (!isOpen) return null;
    
    const bgAlpha = 1 - opacity;
    
    return (
      <Box
            sx={{
          position: 'fixed',
          left: position.x,
          top: position.y,
          width: size.width,
          height: size.height,
          display: 'flex',
          flexDirection: 'column',
          bgcolor: isDark 
            ? `rgba(30, 35, 50, ${bgAlpha * 0.98})` 
            : `rgba(255, 252, 245, ${bgAlpha * 0.98})`,
          borderRadius: '8px',
          boxShadow: isDark 
            ? `0 4px 24px rgba(0,0,0,${bgAlpha * 0.6}), 0 0 0 1px rgba(100, 120, 180, ${bgAlpha * 0.15})`
            : `0 4px 24px rgba(0,0,0,${bgAlpha * 0.15}), 0 0 0 1px rgba(0, 0, 0, ${bgAlpha * 0.08})`,
          border: isDark 
            ? `1px solid rgba(80, 100, 160, ${bgAlpha * 0.4})`
            : `1px solid rgba(180, 160, 140, ${bgAlpha * 0.5})`,
          zIndex: 1300,
          overflow: 'hidden',
          pointerEvents: 'auto',
          backdropFilter: bgAlpha > 0.3 ? 'blur(8px)' : 'none',
        }}
      >
        {/* 헤더 (드래그 영역) */}
        <Box 
          onMouseDown={onDragStart}
          sx={{ 
            display: 'flex', 
            alignItems: 'center', 
            justifyContent: 'space-between',
            px: 1.25,
            py: 1,
            bgcolor: isDark 
              ? `rgba(35, 42, 65, ${bgAlpha * 0.95})` 
              : `rgba(245, 240, 230, ${bgAlpha * 0.95})`,
            borderBottom: `1px solid ${isDark ? 'rgba(70, 85, 130, 0.4)' : 'rgba(200, 185, 165, 0.6)'}`,
            cursor: 'move',
            userSelect: 'none',
          }}
        >
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75 }}>
            <Typography sx={{ fontSize: '14px' }}>{icon}</Typography>
            <Typography sx={{ 
              fontSize: '12px', 
              fontWeight: 700,
              color: isDark ? '#c8d4f0' : '#5a4a35',
              letterSpacing: '0.3px',
            }}>
              {title}
            </Typography>
          </Box>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.25 }}>
            {/* 투명도 슬라이더 */}
            <Box 
              sx={{ 
                display: 'flex', 
                alignItems: 'center', 
                gap: 0.5,
                px: 0.75,
                py: 0.25,
                borderRadius: '4px',
                bgcolor: isDark ? 'rgba(0,0,0,0.2)' : 'rgba(0,0,0,0.05)',
              }}
            >
              <Typography sx={{ 
                fontSize: '9px', 
                color: isDark ? '#71717a' : '#888',
                minWidth: 24,
                textAlign: 'right',
              }}>
                {Math.round(opacity * 100)}%
              </Typography>
              <input
                type="range"
                min="0"
                max="0.95"
                step="0.05"
                value={opacity}
                onChange={(e) => onOpacityChange(parseFloat(e.target.value))}
                style={{ 
                  width: 45, 
                  height: 2, 
                  cursor: 'pointer',
                  accentColor: '#22c55e',
                }}
              />
            </Box>
            <IconButton 
              size="small" 
              onClick={onClose}
              sx={{ 
                p: 0.25,
                ml: 0.25,
                color: isDark ? '#52525b' : '#a1a1aa',
                '&:hover': { 
                  color: isDark ? '#fafafa' : '#333', 
                  bgcolor: isDark ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.05)' 
                }
              }}
            >
              <CloseIcon sx={{ fontSize: 14 }} />
            </IconButton>
          </Box>
        </Box>

        {/* 컨텐츠 */}
        <Box sx={{ 
          p: 1.5, 
          flex: 1,
          overflow: 'auto',
          WebkitOverflowScrolling: 'touch',
          bgcolor: isDark 
            ? `rgba(25, 30, 45, ${bgAlpha * 0.95})` 
            : `rgba(252, 250, 245, ${bgAlpha * 0.95})`,
        }}>
          {children}
        </Box>
        
        {/* 리사이즈 핸들 (우측 하단) */}
        <Box
          onMouseDown={onResizeStart}
          sx={{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: 18,
            height: 18,
            cursor: 'nwse-resize',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            bgcolor: isDark ? 'rgba(70, 85, 130, 0.3)' : 'rgba(200, 185, 165, 0.4)',
            borderTopLeftRadius: 4,
            '&:hover': {
              bgcolor: isDark ? 'rgba(100, 120, 180, 0.5)' : 'rgba(180, 160, 140, 0.6)',
            },
            '&::before': {
              content: '""',
              position: 'absolute',
              right: 4,
              bottom: 4,
              width: 6,
              height: 6,
              borderRight: `2px solid ${isDark ? 'rgba(150, 170, 220, 0.7)' : 'rgba(120, 100, 80, 0.5)'}`,
              borderBottom: `2px solid ${isDark ? 'rgba(150, 170, 220, 0.7)' : 'rgba(120, 100, 80, 0.5)'}`,
            },
          }}
        />
      </Box>
    );
  };

  // 투자성과 팝업 컨텐츠
  const PerformancePopupContent = () => {
    // 추가 통계 계산
    const maxProfit = result?.maxProfit ?? 0;
    const maxLoss = result?.maxLoss ?? 0;
    const avgProfit = result?.avgProfit ?? 0;
    const avgLoss = result?.avgLoss ?? 0;
    const maxConsecutiveWins = result?.maxConsecutiveWins ?? 0;
    const maxConsecutiveLosses = result?.maxConsecutiveLosses ?? 0;
    const maxCapital = result?.maxCapital ?? initialCapital;
    const sharpeRatio = result?.sharpeRatio ?? 0;
    const totalCommission = result?.totalCommission ?? 0;
    const winningTrades = filteredPerformance?.winningTrades ?? (result?.winningTrades ?? 0);
    const losingTrades = filteredPerformance?.losingTrades ?? (result?.losingTrades ?? 0);
    const strategyName = result?.strategyName ?? '선택된 전략 없음';
    
    // 수익 팩터 계산 (총 수익 / 총 손실)
    const totalWinAmount = avgProfit * winningTrades;
    const totalLossAmount = Math.abs(avgLoss) * losingTrades;
    const profitFactor = totalLossAmount > 0 ? (totalWinAmount / totalLossAmount) : totalWinAmount > 0 ? Infinity : 0;
    
    return (
      <Box>
        {/* 전략 정보 */}
        {result && (
          <Box sx={{ 
            mb: 2,
            p: 1.5,
            bgcolor: isDark ? '#1f1f26' : '#f0f4ff',
            borderRadius: 1.5,
            border: `1px solid ${isDark ? '#27272a' : '#dbeafe'}`,
          }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#6b7280' }}>
                적용 전략
              </Typography>
              <Chip 
                label={strategyName}
                size="small"
                sx={{ 
                  fontSize: '10px',
                  height: 20,
                  bgcolor: isDark ? '#3b82f6' : '#2563eb',
                  color: '#fff',
                  fontWeight: 600,
                }}
              />
            </Box>
          </Box>
        )}
        
        {/* 총 수익률 - 메인 카드 */}
        <Box sx={{ 
          textAlign: 'center', 
          p: 2.5, 
          borderRadius: 2,
          mb: 2,
          bgcolor: isProfit 
            ? (isDark ? 'rgba(34, 197, 94, 0.1)' : 'rgba(34, 197, 94, 0.08)')
            : (isDark ? 'rgba(239, 68, 68, 0.1)' : 'rgba(239, 68, 68, 0.08)'),
          border: `1px solid ${isProfit ? 'rgba(34, 197, 94, 0.25)' : 'rgba(239, 68, 68, 0.25)'}`,
          position: 'relative',
          overflow: 'hidden',
        }}>
          {/* 배경 장식 */}
          <Box sx={{ 
            position: 'absolute', 
            top: -20, 
            right: -20, 
            width: 80, 
            height: 80, 
            borderRadius: '50%',
            bgcolor: isProfit ? 'rgba(34, 197, 94, 0.1)' : 'rgba(239, 68, 68, 0.1)',
          }} />
          
          <Typography sx={{ fontSize: '11px', color: isDark ? '#71717a' : '#888', mb: 0.5, position: 'relative' }}>
            총 수익률
          </Typography>
          <Typography sx={{ fontSize: '32px', fontWeight: 800, color: isProfit ? '#22c55e' : '#ef4444', position: 'relative' }}>
            {isProfit ? '+' : ''}{returnRate.toFixed(2)}%
          </Typography>
          <Typography sx={{ fontSize: '14px', fontWeight: 500, color: isProfit ? '#22c55e' : '#ef4444', position: 'relative' }}>
            ₩{Math.round(Math.abs(netProfit)).toLocaleString()}원 {isProfit ? '수익' : '손실'}
          </Typography>
        </Box>
        
        {/* 자산 현황 섹션 */}
        <Box sx={{ mb: 2 }}>
          <Typography sx={{ fontSize: '11px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 1, textTransform: 'uppercase' }}>
            💰 자산 현황
          </Typography>
          <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 1 }}>
            <Box sx={{ bgcolor: isDark ? '#1f1f26' : '#f5f5f5', p: 1.5, borderRadius: 1, textAlign: 'center' }}>
              <Typography sx={{ fontSize: '9px', color: isDark ? '#71717a' : '#888', mb: 0.3 }}>
                초기 자본
              </Typography>
              <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#444' }}>
                ₩{initialCapital.toLocaleString()}
              </Typography>
            </Box>
            <Box sx={{ bgcolor: isDark ? '#1f1f26' : '#f5f5f5', p: 1.5, borderRadius: 1, textAlign: 'center' }}>
              <Typography sx={{ fontSize: '9px', color: isDark ? '#71717a' : '#888', mb: 0.3 }}>
                최종 자산
              </Typography>
              <Typography sx={{ fontSize: '12px', fontWeight: 700, color: isProfit ? '#22c55e' : '#ef4444' }}>
                ₩{Math.round(displayFinalCapital || initialCapital).toLocaleString()}
              </Typography>
            </Box>
            <Box sx={{ bgcolor: isDark ? '#1f1f26' : '#f5f5f5', p: 1.5, borderRadius: 1, textAlign: 'center' }}>
              <Typography sx={{ fontSize: '9px', color: isDark ? '#71717a' : '#888', mb: 0.3 }}>
                최대 자산
              </Typography>
              <Typography sx={{ fontSize: '12px', fontWeight: 600, color: '#3b82f6' }}>
                ₩{Math.round(maxCapital).toLocaleString()}
              </Typography>
            </Box>
          </Box>
        </Box>
        
        {/* 거래 통계 섹션 */}
        <Box sx={{ mb: 2 }}>
          <Typography sx={{ fontSize: '11px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 1, textTransform: 'uppercase' }}>
            📊 거래 통계
          </Typography>
          <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 1 }}>
            <Box sx={{ bgcolor: isDark ? '#1f1f26' : '#f5f5f5', p: 1.5, borderRadius: 1 }}>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>총 거래</Typography>
                <Typography sx={{ fontSize: '13px', fontWeight: 600, color: isDark ? '#fafafa' : '#222' }}>
                  {displayTotalTrades}회
                </Typography>
              </Box>
            </Box>
            <Box sx={{ bgcolor: isDark ? '#1f1f26' : '#f5f5f5', p: 1.5, borderRadius: 1 }}>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>승률</Typography>
                <Typography sx={{ fontSize: '13px', fontWeight: 700, color: displayWinRate >= 50 ? '#22c55e' : '#f59e0b' }}>
                  {displayWinRate.toFixed(1)}%
                </Typography>
              </Box>
            </Box>
            <Box sx={{ bgcolor: isDark ? '#1f1f26' : '#f5f5f5', p: 1.5, borderRadius: 1 }}>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>매수</Typography>
                <Chip 
                  label={`${displayBuyCount}회`}
                  size="small"
                  sx={{ fontSize: '10px', height: 18, bgcolor: 'rgba(34,197,94,0.15)', color: '#22c55e', fontWeight: 600 }}
                />
              </Box>
            </Box>
            <Box sx={{ bgcolor: isDark ? '#1f1f26' : '#f5f5f5', p: 1.5, borderRadius: 1 }}>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>매도</Typography>
                <Chip 
                  label={`${displaySellCount}회`}
                  size="small"
                  sx={{ fontSize: '10px', height: 18, bgcolor: 'rgba(239,68,68,0.15)', color: '#ef4444', fontWeight: 600 }}
                />
              </Box>
            </Box>
            <Box sx={{ bgcolor: isDark ? '#1f1f26' : '#f5f5f5', p: 1.5, borderRadius: 1 }}>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>이긴 거래</Typography>
                <Typography sx={{ fontSize: '12px', fontWeight: 600, color: '#22c55e' }}>
                  {winningTrades}회
                </Typography>
              </Box>
            </Box>
            <Box sx={{ bgcolor: isDark ? '#1f1f26' : '#f5f5f5', p: 1.5, borderRadius: 1 }}>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>진 거래</Typography>
                <Typography sx={{ fontSize: '12px', fontWeight: 600, color: '#ef4444' }}>
                  {losingTrades}회
                </Typography>
              </Box>
            </Box>
          </Box>
        </Box>
        
        {/* 손익 분석 섹션 */}
        <Box sx={{ mb: 2 }}>
          <Typography sx={{ fontSize: '11px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 1, textTransform: 'uppercase' }}>
            📈 손익 분석
          </Typography>
          <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 1 }}>
            <Box sx={{ bgcolor: isDark ? '#1f1f26' : '#f5f5f5', p: 1.5, borderRadius: 1 }}>
              <Typography sx={{ fontSize: '9px', color: isDark ? '#71717a' : '#888', mb: 0.3 }}>최대 수익</Typography>
              <Typography sx={{ fontSize: '12px', fontWeight: 600, color: '#22c55e' }}>
                +₩{Math.round(maxProfit).toLocaleString()}
              </Typography>
            </Box>
            <Box sx={{ bgcolor: isDark ? '#1f1f26' : '#f5f5f5', p: 1.5, borderRadius: 1 }}>
              <Typography sx={{ fontSize: '9px', color: isDark ? '#71717a' : '#888', mb: 0.3 }}>최대 손실</Typography>
              <Typography sx={{ fontSize: '12px', fontWeight: 600, color: '#ef4444' }}>
                -₩{Math.round(Math.abs(maxLoss)).toLocaleString()}
              </Typography>
            </Box>
            <Box sx={{ bgcolor: isDark ? '#1f1f26' : '#f5f5f5', p: 1.5, borderRadius: 1 }}>
              <Typography sx={{ fontSize: '9px', color: isDark ? '#71717a' : '#888', mb: 0.3 }}>평균 수익</Typography>
              <Typography sx={{ fontSize: '12px', fontWeight: 600, color: '#22c55e' }}>
                +₩{Math.round(avgProfit).toLocaleString()}
              </Typography>
            </Box>
            <Box sx={{ bgcolor: isDark ? '#1f1f26' : '#f5f5f5', p: 1.5, borderRadius: 1 }}>
              <Typography sx={{ fontSize: '9px', color: isDark ? '#71717a' : '#888', mb: 0.3 }}>평균 손실</Typography>
              <Typography sx={{ fontSize: '12px', fontWeight: 600, color: '#ef4444' }}>
                -₩{Math.round(Math.abs(avgLoss)).toLocaleString()}
              </Typography>
            </Box>
          </Box>
        </Box>
        
        {/* 연속 기록 & 위험 지표 섹션 */}
        <Box sx={{ mb: 2 }}>
          <Typography sx={{ fontSize: '11px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 1, textTransform: 'uppercase' }}>
            🎯 연속 기록 & 위험 지표
          </Typography>
          <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 1 }}>
            <Box sx={{ bgcolor: isDark ? '#1f1f26' : '#f5f5f5', p: 1.5, borderRadius: 1 }}>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>연속 승리</Typography>
                <Chip 
                  icon={<span style={{ fontSize: '10px' }}>🔥</span>}
                  label={`${maxConsecutiveWins}회`}
                  size="small"
                  sx={{ fontSize: '10px', height: 20, bgcolor: 'rgba(34,197,94,0.15)', color: '#22c55e', fontWeight: 600 }}
                />
              </Box>
            </Box>
            <Box sx={{ bgcolor: isDark ? '#1f1f26' : '#f5f5f5', p: 1.5, borderRadius: 1 }}>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>연속 손실</Typography>
                <Chip 
                  icon={<span style={{ fontSize: '10px' }}>💧</span>}
                  label={`${maxConsecutiveLosses}회`}
                  size="small"
                  sx={{ fontSize: '10px', height: 20, bgcolor: 'rgba(239,68,68,0.15)', color: '#ef4444', fontWeight: 600 }}
                />
              </Box>
            </Box>
            <Box sx={{ bgcolor: isDark ? '#1f1f26' : '#f5f5f5', p: 1.5, borderRadius: 1 }}>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>최대 낙폭(MDD)</Typography>
                <Typography sx={{ fontSize: '12px', fontWeight: 700, color: '#ef4444' }}>
                  {displayMaxDrawdown.toFixed(2)}%
                </Typography>
              </Box>
            </Box>
            <Box sx={{ bgcolor: isDark ? '#1f1f26' : '#f5f5f5', p: 1.5, borderRadius: 1 }}>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>샤프 비율</Typography>
                <Typography sx={{ 
                  fontSize: '12px', 
                  fontWeight: 700, 
                  color: sharpeRatio >= 1 ? '#22c55e' : sharpeRatio >= 0 ? '#f59e0b' : '#ef4444' 
                }}>
                  {sharpeRatio.toFixed(2)}
                </Typography>
              </Box>
            </Box>
          </Box>
        </Box>
        
        {/* 수수료 & 수익 팩터 */}
        <Box sx={{ 
          display: 'grid', 
          gridTemplateColumns: 'repeat(2, 1fr)', 
          gap: 1,
          p: 1.5,
          bgcolor: isDark ? '#18181b' : '#fafafa',
          borderRadius: 1.5,
          border: `1px solid ${isDark ? '#27272a' : '#e5e7eb'}`,
        }}>
          <Box sx={{ textAlign: 'center' }}>
            <Typography sx={{ fontSize: '9px', color: isDark ? '#71717a' : '#888', mb: 0.3 }}>
              총 수수료
            </Typography>
            <Typography sx={{ fontSize: '13px', fontWeight: 600, color: '#f59e0b' }}>
              ₩{Math.round(totalCommission).toLocaleString()}
            </Typography>
          </Box>
          <Box sx={{ textAlign: 'center' }}>
            <Typography sx={{ fontSize: '9px', color: isDark ? '#71717a' : '#888', mb: 0.3 }}>
              수익 팩터
            </Typography>
            <Typography sx={{ 
              fontSize: '13px', 
              fontWeight: 700, 
              color: profitFactor >= 1.5 ? '#22c55e' : profitFactor >= 1 ? '#f59e0b' : '#ef4444' 
            }}>
              {profitFactor === Infinity ? '∞' : profitFactor.toFixed(2)}
            </Typography>
          </Box>
        </Box>
      </Box>
    );
  };

  // 거래내역 팝업 컨텐츠
  const TradeHistoryPopupContent = () => {
    // 통계 계산
    const totalCommission = filteredTradeRecords.reduce((sum, t) => sum + (t.commission || 0), 0);
    const totalProfitLoss = filteredTradeRecords
      .filter(t => t.tradeType === 'SELL')
      .reduce((sum, t) => sum + (t.profitLoss || 0), 0);
    const totalTradeAmount = filteredTradeRecords.reduce((sum, t) => sum + (t.totalAmount || 0), 0);
    
    return (
      <Box>
        {/* 거래내역 헤더 */}
        {filteredTradeRecords.length > 0 && (
          <Box sx={{ 
            mb: 2,
            pb: 1.5,
            borderBottom: `1px solid ${isDark ? '#27272a' : '#e0e0e0'}`,
          }}>
            {/* 상단 요약 정보 */}
            <Box sx={{ 
              display: 'flex', 
              justifyContent: 'space-between', 
              alignItems: 'center',
              mb: 1.5,
            }}>
              <Typography sx={{ fontSize: '13px', fontWeight: 600, color: isDark ? '#fafafa' : '#222' }}>
                총 {filteredTradeRecords.length}건의 거래
              </Typography>
              <Chip 
                label={`매수 ${filteredTradeRecords.filter(t => t.tradeType === 'BUY').length} / 매도 ${filteredTradeRecords.filter(t => t.tradeType === 'SELL').length}`}
                size="small"
                sx={{ 
                  fontSize: '10px',
                  bgcolor: isDark ? '#27272a' : '#e0e0e0',
                  color: isDark ? '#a1a1aa' : '#666',
                }}
              />
            </Box>
            
            {/* 거래 요약 통계 */}
            <Box sx={{ 
              display: 'grid', 
              gridTemplateColumns: 'repeat(3, 1fr)', 
              gap: 1.5,
              p: 1.5,
              bgcolor: isDark ? '#18181b' : '#f5f5f5',
              borderRadius: 1,
            }}>
              <Box sx={{ textAlign: 'center' }}>
                <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888', mb: 0.3 }}>
                  총 거래금액
                </Typography>
                <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#fafafa' : '#222' }}>
                  ₩{totalTradeAmount.toLocaleString()}
                </Typography>
              </Box>
              <Box sx={{ textAlign: 'center' }}>
                <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888', mb: 0.3 }}>
                  총 수수료
                </Typography>
                <Typography sx={{ fontSize: '12px', fontWeight: 600, color: '#f59e0b' }}>
                  ₩{totalCommission.toLocaleString()}
                </Typography>
              </Box>
              <Box sx={{ textAlign: 'center' }}>
                <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888', mb: 0.3 }}>
                  총 손익
                </Typography>
                <Typography sx={{ 
                  fontSize: '12px', 
                  fontWeight: 600, 
                  color: totalProfitLoss >= 0 ? '#22c55e' : '#ef4444' 
                }}>
                  {totalProfitLoss >= 0 ? '+' : ''}₩{totalProfitLoss.toLocaleString()}
                </Typography>
              </Box>
            </Box>
          </Box>
        )}
        
        {/* 거래 목록 */}
        {filteredTradeRecords.length > 0 ? (
          <Box>
            {filteredTradeRecords.map((trade, index) => (
              <Tooltip key={index} title="더블클릭하여 상세 정보 보기" arrow placement="left">
              <Box 
                onDoubleClick={() => handleTradeDoubleClick(trade)}
                sx={{ 
                p: 1.5,
                mb: 1,
                bgcolor: isDark ? '#18181b' : '#f9fafb',
                borderRadius: 1.5,
                border: `1px solid ${isDark ? '#27272a' : '#e5e7eb'}`,
                cursor: 'pointer',
                '&:hover': {
                  bgcolor: isDark ? '#1f1f26' : '#f3f4f6',
                },
              }}>
                {/* 거래 상단: 유형, 시간, 가격 */}
                <Box sx={{ 
                  display: 'flex', 
                  alignItems: 'center', 
                  mb: 1.5,
                  pb: 1,
                  borderBottom: `1px solid ${isDark ? '#27272a' : '#e5e7eb'}`,
                }}>
                  <Box sx={{ 
                    width: 32, height: 32, borderRadius: '50%', mr: 1.5,
                    bgcolor: trade.tradeType === 'BUY' ? '#22c55e' : '#ef4444',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    boxShadow: `0 2px 8px ${trade.tradeType === 'BUY' ? 'rgba(34,197,94,0.3)' : 'rgba(239,68,68,0.3)'}`,
                  }}>
                    <Typography sx={{ fontSize: '12px', fontWeight: 700, color: '#fff' }}>
                      {trade.tradeType === 'BUY' ? 'B' : 'S'}
                    </Typography>
                  </Box>
                  <Box sx={{ flex: 1 }}>
                    <Typography sx={{ fontSize: '13px', fontWeight: 600, color: isDark ? '#fafafa' : '#222' }}>
                      {trade.tradeType === 'BUY' ? '매수' : '매도'}
                    </Typography>
                    <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>
                      {trade.timestamp?.split('T')[0]} {trade.timestamp?.split('T')[1]?.substring(0, 5)}
                    </Typography>
                  </Box>
                  <Box sx={{ textAlign: 'right' }}>
                    <Typography sx={{ fontSize: '14px', fontWeight: 700, color: isDark ? '#fafafa' : '#222' }}>
                      ₩{trade.price?.toLocaleString()}
                    </Typography>
                    {trade.tradeType === 'SELL' && trade.returnRate != null && (
                      <Chip 
                        label={`${trade.returnRate >= 0 ? '+' : ''}${trade.returnRate.toFixed(2)}%`}
                        size="small"
                        sx={{ 
                          fontSize: '10px',
                          height: 18,
                          bgcolor: trade.returnRate >= 0 ? 'rgba(34,197,94,0.15)' : 'rgba(239,68,68,0.15)',
                          color: trade.returnRate >= 0 ? '#22c55e' : '#ef4444',
                          fontWeight: 600,
                        }}
                      />
                    )}
                  </Box>
                </Box>
                
                {/* 거래 상세 정보 그리드 */}
                <Box sx={{ 
                  display: 'grid', 
                  gridTemplateColumns: 'repeat(2, 1fr)', 
                  gap: 1,
                }}>
                  {/* 수량 */}
                  {trade.quantity != null && (
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>
                        수량
                      </Typography>
                      <Typography sx={{ fontSize: '11px', fontWeight: 500, color: isDark ? '#a1a1aa' : '#444' }}>
                        {trade.quantity.toFixed(6)}
                      </Typography>
                    </Box>
                  )}
                  
                  {/* 총 거래금액 */}
                  {trade.totalAmount != null && (
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>
                        거래금액
                      </Typography>
                      <Typography sx={{ fontSize: '11px', fontWeight: 500, color: isDark ? '#a1a1aa' : '#444' }}>
                        ₩{trade.totalAmount.toLocaleString()}
                      </Typography>
                    </Box>
                  )}
                  
                  {/* 수수료 */}
                  {trade.commission != null && trade.commission > 0 && (
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>
                        수수료
                      </Typography>
                      <Typography sx={{ fontSize: '11px', fontWeight: 500, color: '#f59e0b' }}>
                        ₩{trade.commission.toLocaleString()}
                      </Typography>
                    </Box>
                  )}
                  
                  {/* 손익금액 (매도 시) */}
                  {trade.tradeType === 'SELL' && trade.profitLoss != null && (
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>
                        손익금액
                      </Typography>
                      <Typography sx={{ 
                        fontSize: '11px', 
                        fontWeight: 600, 
                        color: trade.profitLoss >= 0 ? '#22c55e' : '#ef4444' 
                      }}>
                        {trade.profitLoss >= 0 ? '+' : ''}₩{trade.profitLoss.toLocaleString()}
                      </Typography>
                    </Box>
                  )}
                  
                  {/* 잔고 */}
                  {trade.balance != null && (
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>
                        잔고
                      </Typography>
                      <Typography sx={{ fontSize: '11px', fontWeight: 500, color: isDark ? '#a1a1aa' : '#444' }}>
                        ₩{trade.balance.toLocaleString()}
                      </Typography>
                    </Box>
                  )}
                  
                  {/* 보유량 */}
                  {trade.holdings != null && (
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>
                        보유량
                      </Typography>
                      <Typography sx={{ fontSize: '11px', fontWeight: 500, color: isDark ? '#a1a1aa' : '#444' }}>
                        {trade.holdings.toFixed(6)}
                      </Typography>
                    </Box>
                  )}
                  
                  {/* 신호 점수 */}
                  {trade.signalScore != null && (
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>
                        신호 점수
                      </Typography>
                      <Chip 
                        label={trade.signalScore.toFixed(1)}
                        size="small"
                        sx={{ 
                          fontSize: '10px',
                          height: 18,
                          bgcolor: trade.signalScore >= 0 
                            ? 'rgba(34,197,94,0.15)' 
                            : 'rgba(239,68,68,0.15)',
                          color: trade.signalScore >= 0 ? '#22c55e' : '#ef4444',
                          fontWeight: 600,
                        }}
                      />
                    </Box>
                  )}
                </Box>
                
                {/* 메모 */}
                {trade.note && (
                  <Box sx={{ 
                    mt: 1, 
                    pt: 1, 
                    borderTop: `1px dashed ${isDark ? '#27272a' : '#e5e7eb'}`,
                  }}>
                    <Typography sx={{ 
                      fontSize: '10px', 
                      color: isDark ? '#a1a1aa' : '#666',
                      fontStyle: 'italic',
                    }}>
                      💡 {trade.note}
                    </Typography>
                  </Box>
                )}
              </Box>
              </Tooltip>
            ))}
          </Box>
        ) : (
          <Box sx={{ textAlign: 'center', py: 4 }}>
            <Typography sx={{ fontSize: '32px', mb: 1 }}>📋</Typography>
            <Typography sx={{ fontSize: '13px', color: isDark ? '#52525b' : '#999' }}>
              거래 내역이 없습니다
            </Typography>
          </Box>
        )}
      </Box>
    );
  };

  // ========== 테마별 레이아웃 ==========

  // 기본 테마 (PC 전용 - 3단 레이아웃)
  const DefaultLayout = () => {
    const getGridColumns = () => {
      if (leftPanelOpen && rightPanelOpen) return '280px 1fr 320px';
      if (leftPanelOpen && !rightPanelOpen) return '280px 1fr';
      if (!leftPanelOpen && rightPanelOpen) return '1fr 320px';
      return '1fr';
    };

    return (
      <Box sx={{
        display: 'grid',
        gridTemplateColumns: getGridColumns(),
        height: 'calc(100vh - 180px)', // 상단 툴바 카드 높이 고려
        bgcolor: themeStyle.backgroundColor,
        overflow: 'hidden',
        position: 'relative',
      }}>
        {/* 왼쪽 패널 */}
        <Box sx={{
          bgcolor: themeStyle.surfaceColor,
          borderRight: `1px solid ${themeStyle.borderColor}`,
          display: leftPanelOpen ? 'flex' : 'none',
          flexDirection: 'column',
          overflow: 'auto',
          WebkitOverflowScrolling: 'touch', // iOS 부드러운 스크롤
          touchAction: 'pan-y', // 세로 스크롤만 허용
        }}>
          <Typography sx={{ 
            p: 2, 
            borderBottom: `1px solid ${themeStyle.borderColor}`,
            fontSize: '12px',
            fontWeight: 600,
            color: themeStyle.textSecondaryColor,
            textTransform: 'uppercase',
          }}>
            전략 설정
                    </Typography>
          {settingsContent}
                  </Box>

        {/* 중앙 차트 영역 */}
                    <Box sx={{ 
          display: 'flex',
          flexDirection: 'column',
          bgcolor: themeStyle.backgroundColor,
          overflow: 'auto',
          position: 'relative',
          WebkitOverflowScrolling: 'touch',
        }}>
          {/* 상단 팝업 버튼 */}
          <Box sx={{
            position: 'absolute',
            top: 8,
            right: 40,
            display: 'flex',
            gap: 1,
            zIndex: 20,
          }}>
            <IconButton
              onClick={() => setPerformancePopupOpen(!performancePopupOpen)}
              sx={{
                bgcolor: performancePopupOpen 
                  ? (isDark ? '#22c55e' : '#16a34a') 
                  : (isDark ? 'rgba(39, 39, 42, 0.9)' : 'rgba(240, 240, 240, 0.9)'),
                color: performancePopupOpen ? '#fff' : (isDark ? '#fafafa' : '#333'),
                '&:hover': { 
                  bgcolor: performancePopupOpen 
                    ? (isDark ? '#16a34a' : '#15803d')
                    : (isDark ? 'rgba(63, 63, 70, 0.9)' : 'rgba(220, 220, 220, 0.9)'),
                },
                boxShadow: '0 2px 8px rgba(0,0,0,0.2)',
                width: 36,
                height: 36,
              }}
              title="투자성과"
            >
              <Typography sx={{ fontSize: '16px' }}>📊</Typography>
            </IconButton>
            <IconButton
              onClick={() => setTradeHistoryPopupOpen(!tradeHistoryPopupOpen)}
              sx={{
                bgcolor: tradeHistoryPopupOpen 
                  ? (isDark ? '#3b82f6' : '#2563eb') 
                  : (isDark ? 'rgba(39, 39, 42, 0.9)' : 'rgba(240, 240, 240, 0.9)'),
                color: tradeHistoryPopupOpen ? '#fff' : (isDark ? '#fafafa' : '#333'),
                '&:hover': { 
                  bgcolor: tradeHistoryPopupOpen 
                    ? (isDark ? '#2563eb' : '#1d4ed8')
                    : (isDark ? 'rgba(63, 63, 70, 0.9)' : 'rgba(220, 220, 220, 0.9)'),
                },
                boxShadow: '0 2px 8px rgba(0,0,0,0.2)',
                width: 36,
                height: 36,
              }}
              title="거래내역"
            >
              <Typography sx={{ fontSize: '16px' }}>📋</Typography>
            </IconButton>
          </Box>

          {/* 토글 버튼 */}
          <Box 
            onClick={() => setLeftPanelOpen(!leftPanelOpen)}
            sx={{ 
              position: 'absolute', left: 0, top: '50%', transform: 'translateY(-50%)',
              width: 24, height: 48, bgcolor: themeStyle.borderColor,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              cursor: 'pointer', zIndex: 10, borderRadius: 1,
              '&:hover': { opacity: 0.8 },
            }}
          >
            {leftPanelOpen ? <ChevronLeft fontSize="small" /> : <ChevronRight fontSize="small" />}
          </Box>
          <Box 
            onClick={() => setRightPanelOpen(!rightPanelOpen)}
            sx={{ 
              position: 'absolute', right: 0, top: '50%', transform: 'translateY(-50%)',
              width: 24, height: 48, bgcolor: isDark ? '#27272a' : '#e0e0e0',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              cursor: 'pointer', zIndex: 10, borderRadius: 1,
              '&:hover': { bgcolor: isDark ? '#3f3f46' : '#d0d0d0' },
            }}
          >
            {rightPanelOpen ? <ChevronRight fontSize="small" /> : <ChevronLeft fontSize="small" />}
          </Box>

          {renderChartHeader()}
          {renderChartArea()}
        </Box>

        {/* 오른쪽 패널 */}
        <Box sx={{
          bgcolor: themeStyle.surfaceColor,
          borderLeft: `1px solid ${themeStyle.borderColor}`,
          display: rightPanelOpen ? 'flex' : 'none',
          flexDirection: 'column',
          overflow: 'auto',
          WebkitOverflowScrolling: 'touch',
          touchAction: 'pan-y',
        }}>
          {resultsContent}
        </Box>

        {/* 모달리스 팝업 */}
        {renderPopup(
          performancePopupOpen,
          () => setPerformancePopupOpen(false),
          "투자 성과",
          "📊",
          performancePopupPos,
          performancePopupOpacity,
          setPerformancePopupOpacity,
          (e: React.MouseEvent) => {
            if ((e.target as HTMLElement).tagName === 'INPUT' || (e.target as HTMLElement).closest('button')) return;
            e.preventDefault();
            setPerfDragging(true);
            perfDragStart.current = { x: e.clientX, y: e.clientY, posX: performancePopupPos.x, posY: performancePopupPos.y };
          },
          <PerformancePopupContent />,
          performancePopupSize,
          (e: React.MouseEvent) => {
            e.preventDefault();
            e.stopPropagation();
            setPerfResizing(true);
            perfResizeStart.current = { x: e.clientX, y: e.clientY, width: performancePopupSize.width, height: performancePopupSize.height };
          }
        )}

        {renderPopup(
          tradeHistoryPopupOpen,
          () => setTradeHistoryPopupOpen(false),
          "거래 내역",
          "📋",
          tradeHistoryPopupPos,
          tradeHistoryPopupOpacity,
          setTradeHistoryPopupOpacity,
          (e: React.MouseEvent) => {
            if ((e.target as HTMLElement).tagName === 'INPUT' || (e.target as HTMLElement).closest('button')) return;
            e.preventDefault();
            setTradeDragging(true);
            tradeDragStart.current = { x: e.clientX, y: e.clientY, posX: tradeHistoryPopupPos.x, posY: tradeHistoryPopupPos.y };
          },
          <TradeHistoryPopupContent />,
          tradeHistoryPopupSize,
          (e: React.MouseEvent) => {
            e.preventDefault();
            e.stopPropagation();
            setTradeResizing(true);
            tradeResizeStart.current = { x: e.clientX, y: e.clientY, width: tradeHistoryPopupSize.width, height: tradeHistoryPopupSize.height };
          }
        )}
      </Box>
    );
  };

  // 컴팩트 테마 (탭 기반 레이아웃)
  const CompactLayout = () => (
    <Box sx={{
      height: 'calc(100vh - 180px)',
      bgcolor: themeStyle.backgroundColor,
      mx: -3,
      my: -2,
      display: 'flex',
      flexDirection: 'column',
      overflow: 'hidden',
    }}>
      {/* 상단 탭 메뉴 */}
      <Box sx={{ 
        bgcolor: themeStyle.surfaceColor,
        borderBottom: `1px solid ${themeStyle.borderColor}`,
      }}>
          <Tabs 
          value={mobileActiveTab} 
          onChange={(_, v) => setMobileActiveTab(v)}
          centered={!isMobile}
          variant={isMobile ? 'fullWidth' : 'standard'}
            sx={{
              '& .MuiTab-root': {
              fontSize: '14px',
                fontWeight: 600,
                color: isDark ? '#71717a' : '#888',
              '&.Mui-selected': { color: '#22c55e' },
                },
            '& .MuiTabs-indicator': { backgroundColor: '#22c55e' },
            }}
          >
          <Tab value="settings" icon={<SettingsIcon />} label="설정" iconPosition="start" />
          <Tab value="chart" icon={<TrendingUp />} label="차트" iconPosition="start" />
          <Tab value="results" icon={<AssessmentIcon />} label="결과" iconPosition="start" />
          </Tabs>
        </Box>

      {/* 탭 컨텐츠 */}
        <Box sx={{ 
          flex: 1, 
          overflow: 'auto',
          WebkitOverflowScrolling: 'touch',
          touchAction: 'pan-y',
        }}>
        {mobileActiveTab === 'settings' && (
          <Box sx={{ bgcolor: themeStyle.surfaceColor, height: '100%' }}>
            {settingsContent}
                </Box>
        )}
        {mobileActiveTab === 'chart' && (
          <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
            {renderChartHeader(true)}
            {renderChartArea('300px')}
                  </Box>
        )}
        {mobileActiveTab === 'results' && (
          <Box sx={{ bgcolor: themeStyle.surfaceColor, height: '100%' }}>
            {resultsContent}
                  </Box>
        )}
                  </Box>
                  </Box>
  );

  // 모던 테마 (카드 기반 대시보드)
  const ModernLayout = () => (
                <Box sx={{ 
      height: 'calc(100vh - 180px)',
      bgcolor: themeStyle.backgroundColor,
      mx: -3,
      my: -2,
      p: 2,
      overflow: 'auto',
      WebkitOverflowScrolling: 'touch',
    }}>
      <Box sx={{ 
        display: 'grid', 
        gridTemplateColumns: { xs: '1fr', md: '1fr 1fr', lg: '300px 1fr 300px' },
        gap: 2,
                      height: '100%', 
      }}>
        {/* 설정 카드 */}
        <Card sx={{ 
          bgcolor: themeStyle.surfaceColor,
          display: { xs: 'none', lg: 'block' },
          borderRadius: `${themeStyle.cardBorderRadius}px`,
          boxShadow: themeStyle.useShadow ? 3 : 0,
        }}>
          <CardContent sx={{ p: 0 }}>
            <Box sx={{ 
              p: 2, 
              borderBottom: `1px solid ${isDark ? '#27272a' : '#e0e0e0'}`,
              display: 'flex',
              alignItems: 'center',
              gap: 1,
            }}>
              <SettingsIcon sx={{ color: themeStyle.primaryColor }} />
              <Typography fontWeight={600}>전략 설정</Typography>
                  </Box>
            {settingsContent}
          </CardContent>
        </Card>
                
        {/* 차트 영역 */}
        <Card sx={{ 
          bgcolor: themeStyle.surfaceColor,
          gridColumn: { xs: '1', md: '1 / -1', lg: '2' },
          display: 'flex',
          flexDirection: 'column',
          minHeight: '500px',
        }}>
          {renderChartHeader(true)}
          {renderChartArea('400px')}
        </Card>

        {/* 결과 카드 */}
        <Card sx={{ 
          bgcolor: themeStyle.surfaceColor,
          display: { xs: 'none', lg: 'block' },
        }}>
          {resultsContent}
        </Card>
                </Box>
                
      {/* 모바일/태블릿용 FAB */}
      {(isMobile || isTablet) && (
        <>
          <Fab 
            color="primary" 
            size="medium"
            onClick={() => setMobileSettingsOpen(true)}
            sx={{ position: 'fixed', bottom: 80, left: 16 }}
          >
            <SettingsIcon />
          </Fab>
          <Fab 
            color="secondary" 
            size="medium"
            onClick={() => setMobileResultsOpen(true)}
            sx={{ position: 'fixed', bottom: 80, right: 16 }}
          >
            <AssessmentIcon />
          </Fab>

          {/* 설정 드로어 */}
          <SwipeableDrawer
            anchor="left"
            open={mobileSettingsOpen}
            onClose={() => setMobileSettingsOpen(false)}
            onOpen={() => setMobileSettingsOpen(true)}
          >
            <Box sx={{ width: 300, bgcolor: themeStyle.surfaceColor, height: '100%' }}>
                    <Box sx={{ 
                p: 2, 
                borderBottom: `1px solid ${themeStyle.borderColor}`,
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
              }}>
                <Typography fontWeight={600}>전략 설정</Typography>
                <IconButton onClick={() => setMobileSettingsOpen(false)}>
                  <CloseIcon />
                </IconButton>
                  </Box>
              {settingsContent}
                </Box>
          </SwipeableDrawer>
                
          {/* 결과 드로어 */}
          <SwipeableDrawer
            anchor="right"
            open={mobileResultsOpen}
            onClose={() => setMobileResultsOpen(false)}
            onOpen={() => setMobileResultsOpen(true)}
          >
            <Box sx={{ width: 320, bgcolor: themeStyle.surfaceColor, height: '100%' }}>
                    <Box sx={{ 
                p: 2, 
                borderBottom: `1px solid ${themeStyle.borderColor}`,
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
              }}>
                <Typography fontWeight={600}>투자 결과</Typography>
                <IconButton onClick={() => setMobileResultsOpen(false)}>
                  <CloseIcon />
                </IconButton>
                  </Box>
              {resultsContent}
                </Box>
          </SwipeableDrawer>
        </>
      )}
            </Box>
  );

  // 다크 프로페셔널 테마 (목업과 동일한 레이아웃)
  const DarkProLayout = () => (
    <Box sx={{ 
      display: 'grid',
      gridTemplateColumns: { xs: '1fr', lg: '260px 1fr 320px' },
      height: 'calc(100vh - 180px)',
      bgcolor: '#09090b',
      mx: -3,
      my: -2,
      overflow: 'hidden',
    }}>
      {/* 좌측 패널 - 전략 설정 & 투자 요약 (PC에서만 표시) */}
      <Box sx={{ 
        bgcolor: themeStyle.surfaceColor,
        borderRight: `1px solid ${themeStyle.borderColor}`,
        display: { xs: 'none', lg: 'flex' },
        flexDirection: 'column',
        height: '100%',
        overflow: 'auto',
        WebkitOverflowScrolling: 'touch',
        touchAction: 'pan-y',
      }}>
        {/* 헤더 */}
        <Box sx={{ 
          p: 2.5, 
          borderBottom: `1px solid ${themeStyle.borderColor}`,
          background: 'linear-gradient(135deg, rgba(168, 85, 247, 0.15), rgba(99, 102, 241, 0.15))',
        }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
            <Box sx={{ 
              width: 36, 
              height: 36, 
              background: 'linear-gradient(135deg, #a855f7, #6366f1)',
              borderRadius: '10px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: '18px',
            }}>
              📊
            </Box>
            <Box>
              <Typography sx={{ fontSize: '15px', fontWeight: 700, color: '#fafafa' }}>
                모의투자 설정
                    </Typography>
              <Typography sx={{ fontSize: '11px', color: '#a1a1aa' }}>
                전략을 설정하고 백테스트를 실행하세요
                    </Typography>
                  </Box>
          </Box>
        </Box>

        {/* 전략 설정 섹션 */}
        <Box sx={{ p: 2.5, borderBottom: `1px solid ${themeStyle.borderColor}`, flex: 1, overflow: 'auto' }}>
          <Typography sx={{ fontSize: '10px', textTransform: 'uppercase', letterSpacing: '1.5px', color: '#52525b', mb: 2 }}>
            전략 설정
                  </Typography>
          
          {/* 종목 */}
          <Box sx={{ mb: 2.5 }}>
            <Typography sx={{ fontSize: '12px', color: '#a1a1aa', mb: 1, display: 'flex', alignItems: 'center', gap: 0.5 }}>
              🪙 종목
            </Typography>
            <CryptoNameComboBox
              value={symbol}
              onChange={handleCryptoChange}
              disabled={loading}
            />
                </Box>
                
          {/* 정배열 전략 */}
          <Box sx={{ mb: 2.5 }}>
            <Typography sx={{ fontSize: '12px', color: '#a1a1aa', mb: 1, display: 'flex', alignItems: 'center', gap: 0.5 }}>
              <TrendingUp sx={{ fontSize: 14, color: '#22c55e' }} />
              정배열 전략
            </Typography>
            <FormControl fullWidth size="small">
              <Select
                value={uptrendStrategy}
                onChange={(e) => setUptrendStrategy(e.target.value as number | '')}
                disabled={loading}
                displayEmpty
                sx={{ 
                  bgcolor: '#27272a', 
                  color: '#fff',
                  borderRadius: '10px',
                  '& .MuiOutlinedInput-notchedOutline': { borderColor: '#3f3f46' },
                  '&:hover .MuiOutlinedInput-notchedOutline': { borderColor: '#22c55e' },
                  '&.Mui-focused .MuiOutlinedInput-notchedOutline': { borderColor: '#22c55e' },
                }}
              >
                <MenuItem value="">선택안함</MenuItem>
                {uptrendRules.map((r) => (
                  <MenuItem key={r.id} value={r.id}>{r.name}</MenuItem>
                ))}
              </Select>
            </FormControl>
          </Box>
          
          {/* 역배열 전략 */}
          <Box sx={{ mb: 2.5 }}>
            <Typography sx={{ fontSize: '12px', color: '#a1a1aa', mb: 1, display: 'flex', alignItems: 'center', gap: 0.5 }}>
              <TrendingDown sx={{ fontSize: 14, color: '#ef4444' }} />
              역배열 전략
            </Typography>
            <FormControl fullWidth size="small">
              <Select
                value={downtrendStrategy}
                onChange={(e) => setDowntrendStrategy(e.target.value as number | '')}
                disabled={loading}
                displayEmpty
                sx={{ 
                  bgcolor: '#27272a', 
                  color: '#fff',
                  borderRadius: '10px',
                  '& .MuiOutlinedInput-notchedOutline': { borderColor: '#3f3f46' },
                  '&:hover .MuiOutlinedInput-notchedOutline': { borderColor: '#ef4444' },
                  '&.Mui-focused .MuiOutlinedInput-notchedOutline': { borderColor: '#ef4444' },
                }}
              >
                <MenuItem value="">선택안함</MenuItem>
                {downtrendRules.map((r) => (
                  <MenuItem key={r.id} value={r.id}>{r.name}</MenuItem>
                ))}
              </Select>
            </FormControl>
          </Box>

          {/* 시간봉 & 기간 */}
          <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 2, mb: 2.5 }}>
            <Box>
              <Typography sx={{ fontSize: '12px', color: '#a1a1aa', mb: 1 }}>
                ⏱️ 시간봉
                    </Typography>
              <FormControl fullWidth size="small">
                <Select
                  value={timeframe}
                  onChange={(e) => handleIntervalChange(e.target.value)}
                  sx={{ 
                    bgcolor: '#27272a', 
                    color: '#fff',
                    borderRadius: '10px',
                    '& .MuiOutlinedInput-notchedOutline': { borderColor: '#3f3f46' },
                  }}
                >
                  <MenuItem value="1m">1분</MenuItem>
                  <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">1일</MenuItem>
                </Select>
              </FormControl>
                  </Box>
            <Box>
              <Typography sx={{ fontSize: '12px', color: '#a1a1aa', mb: 1 }}>
                📅 기간
                    </Typography>
              <FormControl fullWidth size="small">
                <Select
                  value={period}
                  onChange={(e) => handlePeriodChange(e.target.value)}
                  sx={{ 
                    bgcolor: '#27272a', 
                    color: '#fff',
                    borderRadius: '10px',
                    '& fieldset': { borderColor: '#3f3f46' },
                    '& .MuiSelect-icon': { color: '#a1a1aa' },
                  }}
                >
                  <MenuItem value="1day">1일</MenuItem>
                  <MenuItem value="1week">1주일</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>
            </Box>
          </Box>

          {/* 초기자본 */}
          <Box sx={{ mb: 3 }}>
            <Typography sx={{ fontSize: '12px', color: '#a1a1aa', mb: 1 }}>
              💰 초기 투자금
                    </Typography>
            <TextField
              fullWidth
              size="small"
              type="number"
              value={initialCapital}
              onChange={(e) => setInitialCapital(Number(e.target.value))}
              InputProps={{
                startAdornment: <InputAdornment position="start" sx={{ color: '#71717a' }}>₩</InputAdornment>,
              }}
              sx={{ 
                '& .MuiOutlinedInput-root': {
                  bgcolor: '#27272a', 
                  color: '#fff',
                  borderRadius: '10px',
                  '& fieldset': { borderColor: '#3f3f46' },
                },
              }}
            />
                  </Box>

          {/* 실행 버튼 */}
          <Button
            fullWidth
            variant="contained"
            startIcon={loading ? <CircularProgress size={18} color="inherit" /> : <PlayArrow />}
            onClick={handleRunBacktest}
            disabled={loading || (!uptrendStrategy && !downtrendStrategy)}
            sx={{ 
              background: 'linear-gradient(135deg, #a855f7, #6366f1)',
              borderRadius: '12px',
              py: 1.5,
              fontWeight: 600,
              fontSize: '15px',
              boxShadow: '0 4px 15px rgba(168, 85, 247, 0.4)',
              '&:hover': { 
                background: 'linear-gradient(135deg, #9333ea, #4f46e5)',
                boxShadow: '0 6px 20px rgba(168, 85, 247, 0.5)',
              },
            }}
          >
            {loading ? '분석 중...' : '▶ 백테스트 실행'}
          </Button>
        </Box>

        {/* 투자 요약 섹션 */}
        <Box sx={{ p: 2.5 }}>
          <Typography sx={{ fontSize: '10px', textTransform: 'uppercase', letterSpacing: '1.5px', color: '#52525b', mb: 2 }}>
            투자 요약
                    </Typography>
          
          {result ? (
            <>
              {/* 수익률 */}
                    <Box sx={{ 
                p: 2, 
                bgcolor: isProfit ? 'rgba(34, 197, 94, 0.1)' : 'rgba(239, 68, 68, 0.1)',
                borderRadius: '12px',
                border: `1px solid ${isProfit ? 'rgba(34, 197, 94, 0.3)' : 'rgba(239, 68, 68, 0.3)'}`,
                mb: 2,
              }}>
                <Typography sx={{ fontSize: '11px', color: '#71717a', mb: 0.5 }}>총 수익률</Typography>
                <Typography sx={{ 
                  fontSize: '28px', 
                  fontWeight: 700, 
                  color: isProfit ? '#22c55e' : '#ef4444',
                  lineHeight: 1,
                }}>
                  {isProfit ? '+' : ''}{returnRate.toFixed(2)}%
                    </Typography>
                  </Box>

              {/* 상세 정보 */}
              <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Typography sx={{ fontSize: '12px', color: '#71717a' }}>순이익</Typography>
                  <Typography sx={{ fontSize: '13px', fontWeight: 600, color: isProfit ? '#22c55e' : '#ef4444' }}>
                    {netProfit >= 0 ? '+' : ''}₩{(netProfit / 10000).toFixed(0)}만
                    </Typography>
                </Box>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Typography sx={{ fontSize: '12px', color: '#71717a' }}>승률</Typography>
                  <Typography sx={{ fontSize: '13px', fontWeight: 600, color: '#a855f7' }}>
                    {accuracy.overall.toFixed(1)}%
                    </Typography>
                  </Box>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Typography sx={{ fontSize: '12px', color: '#71717a' }}>총 거래</Typography>
                  <Typography sx={{ fontSize: '13px', fontWeight: 600, color: '#fafafa' }}>
                    {result.totalTrades}회
                  </Typography>
                </Box>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Typography sx={{ fontSize: '12px', color: '#71717a' }}>최종 자산</Typography>
                  <Typography sx={{ fontSize: '13px', fontWeight: 600, color: '#fafafa' }}>
                    ₩{result.finalCapital.toLocaleString()}
                  </Typography>
                </Box>
              </Box>
            </>
          ) : (
            <Box sx={{ 
              p: 3, 
              bgcolor: '#27272a',
              borderRadius: '12px',
              textAlign: 'center',
            }}>
              <Typography sx={{ fontSize: '32px', mb: 1 }}>📈</Typography>
              <Typography sx={{ fontSize: '13px', color: '#71717a' }}>
                전략을 선택하고<br />백테스트를 실행하세요
              </Typography>
            </Box>
          )}
                  </Box>
                </Box>
                
      {/* 메인 콘텐츠 (중앙 - 차트 영역) */}
      <Box sx={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
        {/* 톱바 */}
        <Box sx={{ 
          p: '16px 32px', 
          borderBottom: `1px solid ${themeStyle.borderColor}`,
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
        }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 3 }}>
            <Typography sx={{ fontSize: '22px', fontWeight: 600, color: '#fafafa' }}>
              투자전략 백테스트
                </Typography>
            <Chip 
              label="PC-04 다크 프로" 
              size="small"
              sx={{ 
                bgcolor: 'rgba(168, 85, 247, 0.15)',
                color: '#a855f7',
                fontSize: '11px',
              }}
            />
          </Box>
          <Box sx={{ display: 'flex', gap: 1.5 }}>
            <Button 
              variant="outlined"
              sx={{ 
                borderColor: '#27272a', 
                color: '#a1a1aa',
                borderRadius: '8px',
                fontSize: '13px',
              }}
            >
              📥 내보내기
            </Button>
            <Button 
              variant="contained"
              sx={{ 
                background: 'linear-gradient(135deg, #a855f7, #6366f1)',
                borderRadius: '8px',
                fontSize: '13px',
              }}
            >
              + 새 테스트
            </Button>
          </Box>
        </Box>

        {/* 콘텐츠 영역 */}
        <Box sx={{ flex: 1, p: '24px 32px', overflow: 'auto', minHeight: 0, WebkitOverflowScrolling: 'touch' }}>
          {/* 현재 설정 요약 바 (모바일/태블릿용 및 현재 설정 표시) */}
          <Box sx={{ 
            bgcolor: themeStyle.surfaceColor,
            borderRadius: '16px',
            p: '16px 24px',
            display: 'flex',
            gap: 3,
            alignItems: 'center',
            mb: 3,
            flexWrap: 'wrap',
          }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <Typography sx={{ fontSize: '12px', color: '#71717a' }}>종목:</Typography>
              <Chip label={symbol} size="small" sx={{ bgcolor: '#27272a', color: '#fff', fontWeight: 600 }} />
            </Box>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <Typography sx={{ fontSize: '12px', color: '#71717a' }}>정배열:</Typography>
              <Chip 
                label={uptrendRules.find(s => s.id === uptrendStrategy)?.name || '미선택'} 
                size="small" 
                sx={{ bgcolor: 'rgba(34, 197, 94, 0.2)', color: '#22c55e', fontWeight: 600 }} 
              />
            </Box>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <Typography sx={{ fontSize: '12px', color: '#71717a' }}>역배열:</Typography>
              <Chip 
                label={downtrendRules.find(s => s.id === downtrendStrategy)?.name || '미선택'} 
                size="small" 
                sx={{ bgcolor: 'rgba(239, 68, 68, 0.2)', color: '#ef4444', fontWeight: 600 }} 
              />
            </Box>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <Typography sx={{ fontSize: '12px', color: '#71717a' }}>시간봉:</Typography>
              <Chip label={timeframe} size="small" sx={{ bgcolor: '#27272a', color: '#fff' }} />
            </Box>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <Typography sx={{ fontSize: '12px', color: '#71717a' }}>기간:</Typography>
              <Chip label={`${period}개`} size="small" sx={{ bgcolor: '#27272a', color: '#fff' }} />
            </Box>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <Typography sx={{ fontSize: '12px', color: '#71717a' }}>초기자본:</Typography>
              <Chip label={`₩${(initialCapital / 10000).toFixed(0)}만`} size="small" sx={{ bgcolor: '#27272a', color: '#fff' }} />
            </Box>
            {/* 모바일/태블릿에서만 실행 버튼 표시 */}
            <Box sx={{ display: { xs: 'block', lg: 'none' }, ml: 'auto' }}>
              <Button
                variant="contained"
                startIcon={loading ? <CircularProgress size={16} color="inherit" /> : <PlayArrow />}
                onClick={handleRunBacktest}
                disabled={loading || (!uptrendStrategy && !downtrendStrategy)}
                size="small"
                sx={{ 
                  background: 'linear-gradient(135deg, #a855f7, #6366f1)',
                  borderRadius: '8px',
                  fontWeight: 600,
                }}
              >
                {loading ? '실행중' : '실행'}
              </Button>
            </Box>
          </Box>

          {/* 결과 배너 */}
          {result && (
            <Box sx={{ 
              background: 'linear-gradient(135deg, rgba(168, 85, 247, 0.1), rgba(99, 102, 241, 0.1))',
              border: '1px solid rgba(168, 85, 247, 0.2)',
              borderRadius: '20px',
              p: 4,
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              mb: 3,
              flexWrap: 'wrap',
              gap: 2,
            }}>
                <Box>
                <Typography sx={{ fontSize: '28px', fontWeight: 700, color: '#fafafa', mb: 0.5 }}>
                  {symbol} 백테스트 완료
                    </Typography>
                <Typography sx={{ color: '#71717a', fontSize: '14px' }}>
                  {result.strategyName} 전략 • {timeframe} 봉 기준
                    </Typography>
                  </Box>
              <Box sx={{ display: 'flex', gap: 5, textAlign: 'center' }}>
                <Box>
                  <Typography sx={{ 
                    fontSize: '36px', 
                    fontWeight: 700, 
                    color: isProfit ? '#22c55e' : '#ef4444',
                  }}>
                    {isProfit ? '+' : ''}{returnRate.toFixed(1)}%
                  </Typography>
                  <Typography sx={{ fontSize: '12px', color: '#71717a' }}>총 수익률</Typography>
                </Box>
                <Box>
                  <Typography sx={{ fontSize: '36px', fontWeight: 700, color: '#fafafa' }}>
                    ₩{(result.finalCapital / 1000000).toFixed(2)}M
                  </Typography>
                  <Typography sx={{ fontSize: '12px', color: '#71717a' }}>최종 자산</Typography>
                </Box>
              </Box>
            </Box>
          )}

          {/* 메트릭 그리드 (6개) */}
                    <Box sx={{ 
            display: 'grid', 
            gridTemplateColumns: { xs: 'repeat(2, 1fr)', sm: 'repeat(3, 1fr)', lg: 'repeat(6, 1fr)' },
            gap: 2,
            mb: 3,
          }}>
            <Box sx={{ bgcolor: themeStyle.surfaceColor, borderRadius: '12px', p: 2.5, border: `1px solid ${themeStyle.borderColor}` }}>
              <Typography sx={{ fontSize: '20px', mb: 1.5 }}>💰</Typography>
              <Typography sx={{ fontSize: '11px', color: '#71717a', mb: 0.75 }}>투자 수익</Typography>
              <Typography sx={{ fontSize: '22px', fontWeight: 600, color: isProfit ? '#22c55e' : '#ef4444' }}>
                ₩{(netProfit / 10000).toFixed(0)}만
              </Typography>
                  </Box>
            <Box sx={{ bgcolor: themeStyle.surfaceColor, borderRadius: '12px', p: 2.5, border: `1px solid ${themeStyle.borderColor}` }}>
              <Typography sx={{ fontSize: '20px', mb: 1.5 }}>🎯</Typography>
              <Typography sx={{ fontSize: '11px', color: '#71717a', mb: 0.75 }}>승률</Typography>
              <Typography sx={{ fontSize: '22px', fontWeight: 600, color: '#fafafa' }}>
                      {accuracy.overall.toFixed(0)}%
                    </Typography>
                </Box>
            <Box sx={{ bgcolor: themeStyle.surfaceColor, borderRadius: '12px', p: 2.5, border: `1px solid ${themeStyle.borderColor}` }}>
              <Typography sx={{ fontSize: '20px', mb: 1.5 }}>🔄</Typography>
              <Typography sx={{ fontSize: '11px', color: '#71717a', mb: 0.75 }}>총 거래</Typography>
              <Typography sx={{ fontSize: '22px', fontWeight: 600, color: '#fafafa' }}>
                {displayTotalTrades}회
              </Typography>
              </Box>
            <Box sx={{ bgcolor: themeStyle.surfaceColor, borderRadius: '12px', p: 2.5, border: `1px solid ${themeStyle.borderColor}` }}>
              <Typography sx={{ fontSize: '20px', mb: 1.5 }}>✅</Typography>
              <Typography sx={{ fontSize: '11px', color: '#71717a', mb: 0.75 }}>수익 거래</Typography>
              <Typography sx={{ fontSize: '22px', fontWeight: 600, color: '#22c55e' }}>
                {filteredPerformance?.winningTrades || 0}회
              </Typography>
            </Box>
            <Box sx={{ bgcolor: themeStyle.surfaceColor, borderRadius: '12px', p: 2.5, border: `1px solid ${themeStyle.borderColor}` }}>
              <Typography sx={{ fontSize: '20px', mb: 1.5 }}>❌</Typography>
              <Typography sx={{ fontSize: '11px', color: '#71717a', mb: 0.75 }}>손실 거래</Typography>
              <Typography sx={{ fontSize: '22px', fontWeight: 600, color: '#ef4444' }}>
                {result?.losingTrades || 0}회
              </Typography>
            </Box>
            <Box sx={{ bgcolor: themeStyle.surfaceColor, borderRadius: '12px', p: 2.5, border: `1px solid ${themeStyle.borderColor}` }}>
              <Typography sx={{ fontSize: '20px', mb: 1.5 }}>📉</Typography>
              <Typography sx={{ fontSize: '11px', color: '#71717a', mb: 0.75 }}>최대 손실</Typography>
              <Typography sx={{ fontSize: '22px', fontWeight: 600, color: '#ef4444' }}>
                {result ? (((result.maxLoss ?? 0) / initialCapital) * 100).toFixed(1) : 0}%
              </Typography>
            </Box>
          </Box>

          {/* 차트 패널 */}
                    <Box sx={{ 
            bgcolor: themeStyle.surfaceColor,
            borderRadius: '16px',
            p: 3,
            border: `1px solid ${themeStyle.borderColor}`,
          }}>
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2.5 }}>
              <Typography sx={{ fontSize: '15px', fontWeight: 600, color: '#fafafa' }}>
                📈 가격 차트 & 매매 시점
              </Typography>
              <Box sx={{ display: 'flex', bgcolor: '#27272a', p: 0.5, borderRadius: '8px' }}>
                <Button size="small" sx={{ 
                  bgcolor: '#3f3f46', color: '#fff', borderRadius: '6px', fontSize: '12px', px: 1.5 
                }}>캔들</Button>
                <Button size="small" sx={{ color: '#71717a', fontSize: '12px', px: 1.5 }}>라인</Button>
                <Button size="small" sx={{ color: '#71717a', fontSize: '12px', px: 1.5 }}>수익곡선</Button>
              </Box>
            </Box>
            <Box sx={{ minHeight: 600, bgcolor: '#0c0c0e', borderRadius: '12px', overflow: 'auto' }}>
              {loading ? (
                <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 600 }}>
                  <CircularProgress sx={{ color: '#a855f7' }} />
                </Box>
              ) : result ? (
                <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column', gap: 0 }}>
                  {/* 캔들스틱 차트 */}
                  <Box sx={{ flexGrow: 1, minHeight: 400 }}>
                    <CandlestickChart
                      ref={chartRef}
                      data={chartData}
                      indicatorData={result.indicatorData || []}
                      height={400}
                      onCrosshairMove={handleCandleChartCrosshairMove}
                      externalHoverTime={sharedHoverTime}
                      hideNativeCrosshair={true}
                      showTooltip={true}
                      onMarkerClick={(timestamp, tradeType) => handleMarkerClick(timestamp, tradeType as 'BUY' | 'SELL')}
                    />
                  </Box>
                  
                  {/* 보조지표 차트들 */}
                  {indicatorVisibility.settings.volume && (
                    <Box sx={{ height: 120 }}>
                      <IndicatorChart
                        ref={volumeChartRef}
                        type="volume"
                        data={result.indicatorData || []}
                        height={120}
                        onCrosshairMove={handleIndicatorCrosshairMove}
                        externalHoverTime={sharedHoverTime}
                        hideNativeCrosshair={true}
                      />
                    </Box>
                  )}
                  
                  {indicatorVisibility.settings.macdLine && (
                    <Box sx={{ height: 150 }}>
                      <IndicatorChart
                        ref={macdChartRef}
                        type="macd"
                        data={result.indicatorData || []}
                        height={150}
                        onCrosshairMove={handleIndicatorCrosshairMove}
                        externalHoverTime={sharedHoverTime}
                        hideNativeCrosshair={true}
                      />
                    </Box>
                  )}
                </Box>
              ) : (
                <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%', flexDirection: 'column', gap: 1 }}>
                  <Typography sx={{ color: '#52525b' }}>차트를 표시하려면 실행 버튼을 클릭하세요</Typography>
            </Box>
          )}
            </Box>
          </Box>
                  </Box>
                </Box>
                
      {/* 우측 패널 - 정확도 & 최근 거래 (PC에서만 표시) */}
                  <Box sx={{ 
        bgcolor: themeStyle.surfaceColor,
        borderLeft: `1px solid ${themeStyle.borderColor}`,
        display: { xs: 'none', lg: 'flex' },
        flexDirection: 'column',
        height: '100%',
        overflow: 'auto',
        p: 2,
        gap: 2,
        WebkitOverflowScrolling: 'touch',
        touchAction: 'pan-y',
      }}>
        {/* 정확도 카드 */}
        <Box sx={{ 
          bgcolor: '#0c0c0e',
          borderRadius: '16px',
          p: 2.5,
          border: `1px solid ${themeStyle.borderColor}`,
          textAlign: 'center',
        }}>
          <Typography sx={{ fontSize: '14px', fontWeight: 600, color: '#fafafa', mb: 2 }}>
            🎯 전략 정확도
          </Typography>
          <Box sx={{ 
            width: 120, 
            height: 120, 
            margin: '0 auto 16px',
            borderRadius: '50%',
            background: `conic-gradient(#a855f7 0deg ${accuracy.overall * 3.6}deg, #27272a ${accuracy.overall * 3.6}deg 360deg)`,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}>
            <Box sx={{ 
              width: 90, 
              height: 90, 
              bgcolor: '#0c0c0e',
              borderRadius: '50%',
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              justifyContent: 'center',
            }}>
              <Typography sx={{ fontSize: '26px', fontWeight: 700, color: '#a855f7' }}>
                {accuracy.overall.toFixed(0)}%
              </Typography>
              <Typography sx={{ fontSize: '10px', color: '#71717a' }}>정확도</Typography>
            </Box>
          </Box>
          <Box sx={{ textAlign: 'left' }}>
                <Box sx={{ mb: 1.5 }}>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', mb: 0.5 }}>
                <Typography sx={{ color: '#71717a', fontSize: '11px' }}>매수 정확도</Typography>
                <Typography sx={{ color: '#22c55e', fontSize: '11px' }}>{accuracy.buy.toFixed(0)}%</Typography>
              </Box>
              <Box sx={{ height: 5, bgcolor: '#27272a', borderRadius: '3px', overflow: 'hidden' }}>
                <Box sx={{ height: '100%', width: `${accuracy.buy}%`, bgcolor: '#22c55e', borderRadius: '3px' }} />
              </Box>
            </Box>
            <Box>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', mb: 0.5 }}>
                <Typography sx={{ color: '#71717a', fontSize: '11px' }}>매도 정확도</Typography>
                <Typography sx={{ color: '#a855f7', fontSize: '11px' }}>{accuracy.sell.toFixed(0)}%</Typography>
              </Box>
              <Box sx={{ height: 5, bgcolor: '#27272a', borderRadius: '3px', overflow: 'hidden' }}>
                <Box sx={{ height: '100%', width: `${accuracy.sell}%`, background: 'linear-gradient(90deg, #a855f7, #6366f1)', borderRadius: '3px' }} />
              </Box>
            </Box>
          </Box>
        </Box>

        {/* 최근 거래 */}
        <Box sx={{ 
          bgcolor: '#0c0c0e',
          borderRadius: '16px',
          p: 2,
          border: `1px solid ${themeStyle.borderColor}`,
          flex: 1,
          display: 'flex',
          flexDirection: 'column',
          minHeight: 0,
        }}>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1.5 }}>
            <Typography sx={{ fontSize: '14px', fontWeight: 600, color: '#fafafa' }}>
              📋 최근 거래
            </Typography>
            {filteredTradeRecords.length > 0 && (
              <Chip 
                label={`${filteredTradeRecords.length}건`}
                size="small"
                sx={{ fontSize: '10px', bgcolor: '#27272a', color: '#a1a1aa', height: 20 }}
              />
            )}
          </Box>
          <Box sx={{ flex: 1, overflow: 'auto', minHeight: 0, WebkitOverflowScrolling: 'touch' }}>
            {filteredTradeRecords.length > 0 ? filteredTradeRecords.slice(-10).reverse().map((trade, idx) => (
              <Tooltip key={idx} title="더블클릭하여 상세 정보 보기" arrow placement="top">
              <Box 
                onDoubleClick={() => handleTradeDoubleClick(trade)}
                sx={{ 
                display: 'flex', 
                alignItems: 'center', 
                p: 1.5, 
                bgcolor: themeStyle.surfaceColor, 
                borderRadius: '8px',
                mb: 1,
                cursor: 'pointer',
                '&:hover': { bgcolor: '#1f1f26' },
              }}>
                <Box sx={{ 
                  width: 28, 
                  height: 28, 
                  borderRadius: '6px',
                  bgcolor: trade.tradeType === 'BUY' ? 'rgba(34, 197, 94, 0.2)' : 'rgba(239, 68, 68, 0.2)',
                    color: trade.tradeType === 'BUY' ? '#22c55e' : '#ef4444',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: '10px',
                  fontWeight: 700,
                  mr: 1,
                  }}>
                    {trade.tradeType === 'BUY' ? 'B' : 'S'}
                  </Box>
                <Box sx={{ flex: 1, minWidth: 0 }}>
                  <Typography sx={{ fontSize: '11px', fontWeight: 500, color: '#fafafa' }}>
                      {trade.tradeType === 'BUY' ? '매수' : '매도'}
                    </Typography>
                  <Typography sx={{ fontSize: '9px', color: '#52525b', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                    {trade.timestamp}
                    </Typography>
                  </Box>
                  <Box sx={{ textAlign: 'right' }}>
                  <Typography sx={{ fontSize: '10px', color: '#a1a1aa' }}>
                    ₩{(trade.price ?? 0).toLocaleString()}
                    </Typography>
                  {trade.profitLoss !== undefined && (
                    <Typography sx={{ 
                      fontSize: '9px', 
                      fontWeight: 600,
                      color: trade.profitLoss >= 0 ? '#22c55e' : '#ef4444',
                    }}>
                      {trade.profitLoss >= 0 ? '+' : ''}{((trade.profitLoss / trade.totalAmount) * 100).toFixed(1)}%
                    </Typography>
                  )}
                </Box>
              </Box>
              </Tooltip>
            )) : (
              <Box sx={{ textAlign: 'center', py: 3 }}>
                <Typography sx={{ fontSize: '24px', mb: 1 }}>📋</Typography>
                <Typography sx={{ color: '#52525b', fontSize: '11px' }}>
                  {result ? '거래가 발생하지 않았습니다' : '백테스트를 실행하세요'}
                </Typography>
              </Box>
            )}
          </Box>
        </Box>
      </Box>

      {/* 모바일용 FAB */}
      {(isMobile || isTablet) && (
        <Fab 
          size="medium"
          onClick={() => setMobileSettingsOpen(true)}
          sx={{ 
            position: 'fixed', 
            bottom: 80, 
            right: 16,
            background: 'linear-gradient(135deg, #a855f7, #6366f1)',
            color: '#fff',
          }}
        >
          <SettingsIcon />
        </Fab>
      )}

      {/* 모바일 설정 드로어 */}
      <Drawer
        anchor="left"
        open={mobileSettingsOpen}
        onClose={() => setMobileSettingsOpen(false)}
      >
        <Box sx={{ width: 320, bgcolor: themeStyle.surfaceColor, height: '100%' }}>
                    <Box sx={{ 
            p: 2, 
            borderBottom: `1px solid ${themeStyle.borderColor}`,
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            background: 'linear-gradient(135deg, #a855f7, #6366f1)',
          }}>
            <Typography fontWeight={600} sx={{ color: '#fff' }}>전략 설정</Typography>
            <IconButton onClick={() => setMobileSettingsOpen(false)} sx={{ color: '#fff' }}>
              <CloseIcon />
            </IconButton>
                  </Box>
          <Box sx={{ p: 2, '& .MuiTypography-root': { color: '#fafafa' } }}>
            {settingsContent}
                </Box>
        </Box>
      </Drawer>
    </Box>
  );

  // 분석리포트 테마 (비즈니스 리포트 스타일)
  const AnalyticsReportLayout = () => (
    <Box sx={{ 
      minHeight: 'calc(100vh - 80px)',
      bgcolor: themeStyle.backgroundColor,
      mx: -3,
      my: -2,
      p: 3,
    }}>
      {/* 헤더 */}
      <Box sx={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center',
        mb: 3,
      }}>
                <Box>
          <Typography variant="h4" sx={{ fontWeight: 700, color: '#f1f5f9', mb: 0.5 }}>
            📊 투자 분석 리포트
                    </Typography>
          <Typography sx={{ color: '#94a3b8', fontSize: '14px' }}>
            {symbol} • {uptrendStrategy ? strategyRules.find(r => r.id === uptrendStrategy)?.name : '정배열 미선택'} / {downtrendStrategy ? strategyRules.find(r => r.id === downtrendStrategy)?.name : '역배열 미선택'} • {new Date().toLocaleDateString('ko-KR')}
                    </Typography>
                  </Box>
        <Box sx={{ display: 'flex', gap: 2 }}>
          <Chip 
            label="PC-02 분석리포트" 
            sx={{ bgcolor: 'rgba(59, 130, 246, 0.15)', color: '#3b82f6' }}
          />
          <Button 
            variant="contained"
            startIcon={loading ? <CircularProgress size={16} color="inherit" /> : <PlayArrow />}
            onClick={handleRunBacktest}
            disabled={loading || (!uptrendStrategy && !downtrendStrategy)}
            sx={{ 
              bgcolor: '#3b82f6',
              borderRadius: '12px',
              px: 3,
              '&:hover': { bgcolor: '#2563eb' },
            }}
          >
            {loading ? '분석 중...' : '백테스트 실행'}
          </Button>
        </Box>
      </Box>

      {/* 설정 카드 */}
      <Card sx={{ 
        bgcolor: themeStyle.surfaceColor, 
        borderRadius: '16px', 
        mb: 3,
        border: '1px solid #334155',
      }}>
        <CardContent sx={{ p: 3 }}>
          <Typography sx={{ fontSize: '13px', fontWeight: 600, color: '#94a3b8', mb: 2, textTransform: 'uppercase', letterSpacing: '0.5px' }}>
            분석 설정
          </Typography>
                    <Box sx={{ 
            display: 'grid', 
            gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, 1fr)', md: 'repeat(5, 1fr)' },
            gap: 2,
          }}>
            <Box>
              <Typography sx={{ fontSize: '11px', color: '#64748b', mb: 0.75 }}>종목</Typography>
              <CryptoNameComboBox
                value={symbol}
                onChange={handleCryptoChange}
                disabled={loading}
              />
                  </Box>
            <Box>
              <Typography sx={{ fontSize: '11px', color: '#64748b', mb: 0.75, display: 'flex', alignItems: 'center', gap: 0.5 }}>
                <TrendingUp sx={{ fontSize: 12, color: '#22c55e' }} />
                정배열 전략
              </Typography>
              <FormControl fullWidth size="small">
                <Select
                  value={uptrendStrategy}
                  onChange={(e) => setUptrendStrategy(e.target.value as number | '')}
                  disabled={loading}
                  displayEmpty
                  sx={{ 
                    bgcolor: themeStyle.backgroundColor, 
                    color: '#f1f5f9',
                    '& .MuiOutlinedInput-notchedOutline': { borderColor: themeStyle.borderColor },
                  }}
                >
                  <MenuItem value="">선택안함</MenuItem>
                  {uptrendRules.map((r) => (
                    <MenuItem key={r.id} value={r.id}>{r.name}</MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Box>
            <Box>
              <Typography sx={{ fontSize: '11px', color: '#64748b', mb: 0.75, display: 'flex', alignItems: 'center', gap: 0.5 }}>
                <TrendingDown sx={{ fontSize: 12, color: '#ef4444' }} />
                역배열 전략
              </Typography>
              <FormControl fullWidth size="small">
                <Select
                  value={downtrendStrategy}
                  onChange={(e) => setDowntrendStrategy(e.target.value as number | '')}
                  disabled={loading}
                  displayEmpty
                  sx={{ 
                    bgcolor: themeStyle.backgroundColor, 
                    color: '#f1f5f9',
                    '& .MuiOutlinedInput-notchedOutline': { borderColor: themeStyle.borderColor },
                  }}
                >
                  <MenuItem value="">선택안함</MenuItem>
                  {downtrendRules.map((r) => (
                    <MenuItem key={r.id} value={r.id}>{r.name}</MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Box>
            <Box>
              <Typography sx={{ fontSize: '11px', color: '#64748b', mb: 0.75 }}>시간봉</Typography>
              <FormControl fullWidth size="small">
                <Select
                  value={timeframe}
                  onChange={(e) => handleIntervalChange(e.target.value)}
                  sx={{ 
                    bgcolor: themeStyle.backgroundColor, 
                    color: '#f1f5f9',
                    '& .MuiOutlinedInput-notchedOutline': { borderColor: themeStyle.borderColor },
                  }}
                >
                  <MenuItem value="1m">1분</MenuItem>
                  <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">1일</MenuItem>
                </Select>
              </FormControl>
              </Box>
            <Box>
              <Typography sx={{ fontSize: '11px', color: '#64748b', mb: 0.75 }}>분석 기간</Typography>
              <FormControl fullWidth size="small">
                <Select
                  value={period}
                  onChange={(e) => handlePeriodChange(e.target.value)}
                  sx={{ 
                    bgcolor: themeStyle.backgroundColor, 
                    color: '#f1f5f9',
                    '& fieldset': { borderColor: themeStyle.borderColor },
                    '& .MuiSelect-icon': { color: '#64748b' },
                  }}
                >
                  <MenuItem value="1day">1일</MenuItem>
                  <MenuItem value="1week">1주일</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>
            </Box>
            <Box>
              <Typography sx={{ fontSize: '11px', color: '#64748b', mb: 0.75 }}>초기 투자금</Typography>
              <TextField
                fullWidth
                size="small"
                type="number"
                value={initialCapital}
                onChange={(e) => setInitialCapital(Number(e.target.value))}
                InputProps={{
                  startAdornment: <InputAdornment position="start" sx={{ color: '#64748b' }}>₩</InputAdornment>,
                }}
                sx={{ 
                  '& .MuiOutlinedInput-root': {
                    bgcolor: themeStyle.backgroundColor, 
                    color: '#f1f5f9',
                    '& fieldset': { borderColor: themeStyle.borderColor },
                  },
                }}
              />
            </Box>
          </Box>
        </CardContent>
      </Card>

      {/* 주요 지표 카드 그리드 */}
                  <Box sx={{ 
        display: 'grid', 
        gridTemplateColumns: { xs: '1fr 1fr', md: 'repeat(4, 1fr)' },
        gap: 2,
        mb: 3,
      }}>
        {/* 총 수익률 */}
        <Card sx={{ 
          bgcolor: isProfit ? 'rgba(34, 197, 94, 0.1)' : 'rgba(239, 68, 68, 0.1)',
          borderRadius: '16px',
          border: `1px solid ${isProfit ? 'rgba(34, 197, 94, 0.3)' : 'rgba(239, 68, 68, 0.3)'}`,
        }}>
          <CardContent sx={{ p: 2.5 }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
              <Box sx={{ 
                width: 36, height: 36, borderRadius: '10px',
                bgcolor: isProfit ? 'rgba(34, 197, 94, 0.2)' : 'rgba(239, 68, 68, 0.2)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: '18px',
              }}>
                📈
                  </Box>
              <Typography sx={{ fontSize: '12px', color: '#94a3b8' }}>총 수익률</Typography>
            </Box>
            <Typography sx={{ 
              fontSize: '32px', 
              fontWeight: 700, 
              color: isProfit ? '#22c55e' : '#ef4444',
              lineHeight: 1,
            }}>
              {isProfit ? '+' : ''}{returnRate.toFixed(2)}%
                    </Typography>
          </CardContent>
        </Card>

        {/* 순이익 */}
        <Card sx={{ 
          bgcolor: themeStyle.surfaceColor,
          borderRadius: '16px',
          border: '1px solid #334155',
        }}>
          <CardContent sx={{ p: 2.5 }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
              <Box sx={{ 
                width: 36, height: 36, borderRadius: '10px',
                bgcolor: 'rgba(59, 130, 246, 0.2)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: '18px',
              }}>
                💰
              </Box>
              <Typography sx={{ fontSize: '12px', color: '#94a3b8' }}>순이익</Typography>
            </Box>
            <Typography sx={{ 
              fontSize: '28px', 
              fontWeight: 700, 
              color: isProfit ? '#22c55e' : '#ef4444',
              lineHeight: 1,
            }}>
              {netProfit >= 0 ? '+' : ''}₩{(netProfit / 10000).toFixed(0)}만
                    </Typography>
          </CardContent>
        </Card>

        {/* 승률 */}
        <Card sx={{ 
          bgcolor: themeStyle.surfaceColor,
          borderRadius: '16px',
          border: '1px solid #334155',
        }}>
          <CardContent sx={{ p: 2.5 }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
              <Box sx={{ 
                width: 36, height: 36, borderRadius: '10px',
                bgcolor: 'rgba(139, 92, 246, 0.2)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: '18px',
              }}>
                🎯
                  </Box>
              <Typography sx={{ fontSize: '12px', color: '#94a3b8' }}>승률</Typography>
            </Box>
            <Typography sx={{ 
              fontSize: '28px', 
              fontWeight: 700, 
              color: '#8b5cf6',
              lineHeight: 1,
            }}>
              {accuracy.overall.toFixed(1)}%
                    </Typography>
          </CardContent>
        </Card>

        {/* 총 거래 */}
        <Card sx={{ 
          bgcolor: themeStyle.surfaceColor,
          borderRadius: '16px',
          border: '1px solid #334155',
        }}>
          <CardContent sx={{ p: 2.5 }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
              <Box sx={{ 
                width: 36, height: 36, borderRadius: '10px',
                bgcolor: 'rgba(14, 165, 233, 0.2)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: '18px',
              }}>
                🔄
              </Box>
              <Typography sx={{ fontSize: '12px', color: '#94a3b8' }}>총 거래</Typography>
            </Box>
                    <Typography sx={{ 
              fontSize: '28px', 
              fontWeight: 700, 
              color: '#f1f5f9',
              lineHeight: 1,
            }}>
              {displayTotalTrades}회
            </Typography>
          </CardContent>
        </Card>
      </Box>

      {/* 차트 + 상세 분석 */}
      <Box sx={{ 
        display: 'grid', 
        gridTemplateColumns: { xs: '1fr', lg: '2fr 1fr' },
        gap: 3,
        mb: 3,
      }}>
        {/* 차트 카드 */}
        <Card sx={{ 
          bgcolor: themeStyle.surfaceColor,
          borderRadius: '16px',
          border: '1px solid #334155',
        }}>
          <CardContent sx={{ p: 0 }}>
            <Box sx={{ 
              p: 2, 
              borderBottom: '1px solid #334155',
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
            }}>
              <Typography sx={{ fontSize: '14px', fontWeight: 600, color: '#f1f5f9' }}>
                📈 가격 차트 & 매매 신호
              </Typography>
              <Box sx={{ display: 'flex', gap: 1 }}>
                <IconButton 
                  size="small" 
                  onClick={handlePreviousPeriod}
                  disabled={loading || isPeriodLoading || !canGoPrevious()}
                  sx={{ color: '#94a3b8' }}
                >
                  <ChevronLeft />
                </IconButton>
                <Chip label={timeframe} size="small" sx={{ bgcolor: '#334155', color: '#f1f5f9' }} />
                <IconButton 
                  size="small" 
                  onClick={handleNextPeriod}
                  disabled={loading || isPeriodLoading || !canGoNext()}
                  sx={{ color: '#94a3b8' }}
                >
                  <ChevronRight />
                </IconButton>
              </Box>
            </Box>
            <Box sx={{ minHeight: 500, bgcolor: themeStyle.backgroundColor }}>
              {loading ? (
                <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 500 }}>
                  <CircularProgress sx={{ color: '#3b82f6' }} />
                </Box>
              ) : result ? (
                <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column', gap: 0 }}>
                  <Box sx={{ flexGrow: 1, minHeight: 400 }}>
                    <CandlestickChart
                      ref={chartRef}
                      data={chartData}
                      indicatorData={result.indicatorData || []}
                      height={400}
                      onCrosshairMove={handleCandleChartCrosshairMove}
                      externalHoverTime={sharedHoverTime}
                      hideNativeCrosshair={true}
                      showTooltip={true}
                      onMarkerClick={(timestamp, tradeType) => handleMarkerClick(timestamp, tradeType as 'BUY' | 'SELL')}
                    />
                  </Box>
                  
                  {indicatorVisibility.settings.volume && (
                    <Box sx={{ height: 120 }}>
                      <IndicatorChart
                        ref={volumeChartRef}
                        type="volume"
                        data={result.indicatorData || []}
                        height={120}
                        onCrosshairMove={handleIndicatorCrosshairMove}
                        externalHoverTime={sharedHoverTime}
                        hideNativeCrosshair={true}
                      />
                    </Box>
                  )}
                </Box>
              ) : (
                <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 500, flexDirection: 'column', gap: 2 }}>
                  <Typography sx={{ fontSize: '48px' }}>📊</Typography>
                  <Typography sx={{ color: '#64748b' }}>백테스트를 실행하면 차트가 표시됩니다</Typography>
                </Box>
              )}
            </Box>
          </CardContent>
        </Card>

        {/* 상세 분석 카드 */}
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          {/* 정확도 분석 */}
          <Card sx={{ 
            bgcolor: themeStyle.surfaceColor,
            borderRadius: '16px',
            border: '1px solid #334155',
          }}>
            <CardContent sx={{ p: 2.5 }}>
              <Typography sx={{ fontSize: '13px', fontWeight: 600, color: '#94a3b8', mb: 2, textTransform: 'uppercase', letterSpacing: '0.5px' }}>
                정확도 분석
              </Typography>
              <Box sx={{ mb: 2 }}>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 0.5 }}>
                  <Typography sx={{ fontSize: '12px', color: '#94a3b8' }}>전체 정확도</Typography>
                  <Typography sx={{ fontSize: '12px', color: '#8b5cf6', fontWeight: 600 }}>{accuracy.overall.toFixed(1)}%</Typography>
                </Box>
                <Box sx={{ height: 8, bgcolor: themeStyle.backgroundColor, borderRadius: '4px', overflow: 'hidden' }}>
                  <Box sx={{ height: '100%', width: `${accuracy.overall}%`, bgcolor: '#8b5cf6', borderRadius: '4px' }} />
                </Box>
              </Box>
              <Box sx={{ mb: 2 }}>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 0.5 }}>
                  <Typography sx={{ fontSize: '12px', color: '#94a3b8' }}>매수 정확도</Typography>
                  <Typography sx={{ fontSize: '12px', color: '#22c55e', fontWeight: 600 }}>{accuracy.buy.toFixed(1)}%</Typography>
                </Box>
                <Box sx={{ height: 8, bgcolor: themeStyle.backgroundColor, borderRadius: '4px', overflow: 'hidden' }}>
                  <Box sx={{ height: '100%', width: `${accuracy.buy}%`, bgcolor: '#22c55e', borderRadius: '4px' }} />
                </Box>
              </Box>
              <Box>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 0.5 }}>
                  <Typography sx={{ fontSize: '12px', color: '#94a3b8' }}>매도 정확도</Typography>
                  <Typography sx={{ fontSize: '12px', color: '#ef4444', fontWeight: 600 }}>{accuracy.sell.toFixed(1)}%</Typography>
                </Box>
                <Box sx={{ height: 8, bgcolor: themeStyle.backgroundColor, borderRadius: '4px', overflow: 'hidden' }}>
                  <Box sx={{ height: '100%', width: `${accuracy.sell}%`, bgcolor: '#ef4444', borderRadius: '4px' }} />
                </Box>
              </Box>
            </CardContent>
          </Card>

          {/* 자산 현황 */}
          <Card sx={{ 
            bgcolor: themeStyle.surfaceColor,
            borderRadius: '16px',
            border: '1px solid #334155',
          }}>
            <CardContent sx={{ p: 2.5 }}>
              <Typography sx={{ fontSize: '13px', fontWeight: 600, color: '#94a3b8', mb: 2, textTransform: 'uppercase', letterSpacing: '0.5px' }}>
                자산 현황
              </Typography>
              <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}>
                <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                  <Typography sx={{ fontSize: '13px', color: '#94a3b8' }}>초기 투자금</Typography>
                  <Typography sx={{ fontSize: '13px', color: '#f1f5f9', fontWeight: 500 }}>₩{initialCapital.toLocaleString()}</Typography>
                </Box>
                <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                  <Typography sx={{ fontSize: '13px', color: '#94a3b8' }}>최종 자산</Typography>
                  <Typography sx={{ fontSize: '13px', color: '#f1f5f9', fontWeight: 500 }}>₩{(displayFinalCapital || initialCapital).toLocaleString()}</Typography>
                </Box>
                <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                  <Typography sx={{ fontSize: '13px', color: '#94a3b8' }}>최대 수익</Typography>
                  <Typography sx={{ fontSize: '13px', color: '#22c55e', fontWeight: 500 }}>₩{(result?.maxProfit ?? 0).toLocaleString()}</Typography>
                </Box>
                <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                  <Typography sx={{ fontSize: '13px', color: '#94a3b8' }}>최대 손실</Typography>
                  <Typography sx={{ fontSize: '13px', color: '#ef4444', fontWeight: 500 }}>₩{(result?.maxLoss ?? 0).toLocaleString()}</Typography>
                </Box>
              </Box>
            </CardContent>
          </Card>

          {/* 거래 통계 */}
          <Card sx={{ 
            bgcolor: themeStyle.surfaceColor,
            borderRadius: '16px',
            border: '1px solid #334155',
          }}>
            <CardContent sx={{ p: 2.5 }}>
              <Typography sx={{ fontSize: '13px', fontWeight: 600, color: '#94a3b8', mb: 2, textTransform: 'uppercase', letterSpacing: '0.5px' }}>
                거래 통계
              </Typography>
              <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 2 }}>
                <Box sx={{ textAlign: 'center', p: 1.5, bgcolor: themeStyle.backgroundColor, borderRadius: '12px' }}>
                  <Typography sx={{ fontSize: '24px', fontWeight: 700, color: '#22c55e' }}>
                    {result?.winningTrades || 0}
                  </Typography>
                  <Typography sx={{ fontSize: '11px', color: '#64748b' }}>수익 거래</Typography>
                </Box>
                <Box sx={{ textAlign: 'center', p: 1.5, bgcolor: themeStyle.backgroundColor, borderRadius: '12px' }}>
                  <Typography sx={{ fontSize: '24px', fontWeight: 700, color: '#ef4444' }}>
                    {result?.losingTrades || 0}
                  </Typography>
                  <Typography sx={{ fontSize: '11px', color: '#64748b' }}>손실 거래</Typography>
                </Box>
              </Box>
            </CardContent>
          </Card>
        </Box>
      </Box>

      {/* 거래 내역 테이블 */}
      <Card sx={{ 
        bgcolor: themeStyle.surfaceColor,
        borderRadius: '16px',
        border: '1px solid #334155',
      }}>
        <CardContent sx={{ p: 0 }}>
          <Box sx={{ p: 2, borderBottom: '1px solid #334155', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Typography sx={{ fontSize: '14px', fontWeight: 600, color: '#f1f5f9' }}>
              📋 거래 내역
            </Typography>
            {filteredTradeRecords.length > 0 ? (
              <Chip 
                label={`총 ${filteredTradeRecords.length}건 (매수 ${filteredTradeRecords.filter(t => t.tradeType === 'BUY').length} / 매도 ${filteredTradeRecords.filter(t => t.tradeType === 'SELL').length})`}
                size="small"
                sx={{ fontSize: '11px', bgcolor: '#334155', color: '#94a3b8' }}
              />
            ) : null}
          </Box>
          <Box sx={{ maxHeight: 300, overflow: 'auto', WebkitOverflowScrolling: 'touch' }}>
            {filteredTradeRecords.length > 0 ? (
              <Box component="table" sx={{ width: '100%', borderCollapse: 'collapse' }}>
                <Box component="thead" sx={{ bgcolor: themeStyle.backgroundColor, position: 'sticky', top: 0 }}>
                  <Box component="tr">
                    <Box component="th" sx={{ p: 1.5, textAlign: 'left', color: '#64748b', fontSize: '11px', fontWeight: 600 }}>유형</Box>
                    <Box component="th" sx={{ p: 1.5, textAlign: 'left', color: '#64748b', fontSize: '11px', fontWeight: 600 }}>시간</Box>
                    <Box component="th" sx={{ p: 1.5, textAlign: 'right', color: '#64748b', fontSize: '11px', fontWeight: 600 }}>가격</Box>
                    <Box component="th" sx={{ p: 1.5, textAlign: 'right', color: '#64748b', fontSize: '11px', fontWeight: 600 }}>수량</Box>
                    <Box component="th" sx={{ p: 1.5, textAlign: 'right', color: '#64748b', fontSize: '11px', fontWeight: 600 }}>손익</Box>
                  </Box>
                </Box>
                <Box component="tbody">
                  {filteredTradeRecords.slice(-20).reverse().map((trade, idx) => (
                    <Tooltip key={idx} title="더블클릭하여 상세 정보 보기" arrow placement="left">
                    <Box 
                      component="tr"
                      onDoubleClick={() => handleTradeDoubleClick(trade)}
                      sx={{ 
                        borderBottom: '1px solid #334155',
                        '&:hover': { bgcolor: 'rgba(59, 130, 246, 0.05)' },
                        cursor: 'pointer',
                      }}
                    >
                      <Box component="td" sx={{ p: 1.5 }}>
                        <Chip 
                          label={trade.tradeType === 'BUY' ? '매수' : '매도'}
                          size="small"
                          sx={{ 
                            bgcolor: trade.tradeType === 'BUY' ? 'rgba(34, 197, 94, 0.2)' : 'rgba(239, 68, 68, 0.2)',
                            color: trade.tradeType === 'BUY' ? '#22c55e' : '#ef4444',
                      fontSize: '11px', 
                      fontWeight: 600,
                          }}
                        />
                      </Box>
                      <Box component="td" sx={{ p: 1.5, color: '#94a3b8', fontSize: '12px' }}>{trade.timestamp}</Box>
                      <Box component="td" sx={{ p: 1.5, textAlign: 'right', color: '#f1f5f9', fontSize: '12px' }}>₩{(trade.price ?? 0).toLocaleString()}</Box>
                      <Box component="td" sx={{ p: 1.5, textAlign: 'right', color: '#94a3b8', fontSize: '12px' }}>{(trade.quantity ?? 0).toFixed(6)}</Box>
                      <Box component="td" sx={{ p: 1.5, textAlign: 'right' }}>
                        {trade.profitLoss != null ? (
                          <Typography sx={{ 
                            fontSize: '12px', 
                            fontWeight: 600,
                            color: trade.profitLoss >= 0 ? '#22c55e' : '#ef4444',
                          }}>
                            {trade.profitLoss >= 0 ? '+' : ''}₩{trade.profitLoss.toLocaleString()}
                    </Typography>
                        ) : (
                          <Typography sx={{ fontSize: '12px', color: '#64748b' }}>-</Typography>
                        )}
                  </Box>
                </Box>
                    </Tooltip>
              ))}
                </Box>
              </Box>
            ) : (
              <Box sx={{ p: 4, textAlign: 'center' }}>
                <Typography sx={{ fontSize: '32px', mb: 1 }}>📋</Typography>
                <Typography sx={{ color: '#64748b', fontSize: '13px', mb: 0.5 }}>
                  {result ? '해당 기간에 거래가 발생하지 않았습니다' : '거래 내역이 없습니다'}
                </Typography>
                {!result && (
                  <Typography sx={{ color: '#475569', fontSize: '11px' }}>
                    백테스트 실행 버튼을 클릭하여 분석을 시작하세요
                  </Typography>
                )}
              </Box>
            )}
          </Box>
        </CardContent>
      </Card>

      {/* 모바일용 FAB */}
      {(isMobile || isTablet) && (
        <Fab 
          size="medium"
          onClick={() => setMobileSettingsOpen(true)}
          sx={{ 
            position: 'fixed', 
            bottom: 80, 
            right: 16,
            bgcolor: '#3b82f6',
            color: '#fff',
            '&:hover': { bgcolor: '#2563eb' },
          }}
        >
          <SettingsIcon />
        </Fab>
      )}

      {/* 모바일 설정 드로어 */}
      <Drawer
        anchor="left"
        open={mobileSettingsOpen}
        onClose={() => setMobileSettingsOpen(false)}
      >
        <Box sx={{ width: 320, bgcolor: themeStyle.surfaceColor, height: '100%' }}>
                <Box sx={{ 
            p: 2, 
            borderBottom: '1px solid #334155',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            bgcolor: '#3b82f6',
          }}>
            <Typography fontWeight={600} sx={{ color: '#fff' }}>분석 설정</Typography>
            <IconButton onClick={() => setMobileSettingsOpen(false)} sx={{ color: '#fff' }}>
              <CloseIcon />
            </IconButton>
          </Box>
          <Box sx={{ p: 2, '& .MuiTypography-root': { color: '#f1f5f9' } }}>
            {settingsContent}
          </Box>
        </Box>
      </Drawer>
    </Box>
  );

  // 스플릿뷰 테마 (좌우 50:50 분할)
  const SplitViewLayout = () => {
    const [splitTab, setSplitTab] = useState<'settings' | 'results'>('settings');
    
    return (
      <Box sx={{ 
        display: 'grid',
        gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' },
        height: 'calc(100vh - 180px)', // 상단 툴바 카드 높이 고려
        bgcolor: themeStyle.backgroundColor,
        overflow: 'hidden',
      }}>
        {/* 왼쪽 패널: 설정/결과 */}
        <Box sx={{ 
          bgcolor: themeStyle.surfaceColor,
          borderRight: `1px solid ${themeStyle.borderColor}`,
          display: 'flex',
          flexDirection: 'column',
          minHeight: 0, // flex 자식 요소의 스크롤 작동을 위해 필요
          overflow: 'hidden',
        }}>
          {/* 헤더 */}
          <Box sx={{ 
            p: 2, 
            borderBottom: `1px solid ${themeStyle.borderColor}`,
            bgcolor: themeStyle.backgroundColor,
          }}>
            <Typography variant="h6" sx={{ 
              fontWeight: 700, 
              color: themeStyle.textColor,
              mb: 1,
            }}>
              📊 모의투자 백테스트
            </Typography>
            <Typography variant="body2" sx={{ color: themeStyle.textSecondaryColor }}>
              {symbol} • 스플릿뷰 테마
            </Typography>
          </Box>

          {/* 탭 */}
          <Box sx={{ borderBottom: `1px solid ${themeStyle.borderColor}` }}>
            <Tabs 
              value={splitTab} 
              onChange={(_, v) => setSplitTab(v)}
              sx={{
                '& .MuiTab-root': { 
                  color: themeStyle.textSecondaryColor,
                  fontWeight: 600,
                  '&.Mui-selected': { color: themeStyle.primaryColor },
                },
                '& .MuiTabs-indicator': { backgroundColor: themeStyle.primaryColor },
              }}
            >
              <Tab value="settings" label="전략 설정" />
              <Tab value="results" label="투자 결과" />
            </Tabs>
          </Box>

          {/* 탭 콘텐츠 */}
          <Box sx={{ 
            flex: 1, 
            overflow: 'auto',
            minHeight: 0, // flex 자식 요소의 스크롤 작동을 위해 필요
            WebkitOverflowScrolling: 'touch',
            touchAction: 'pan-y',
          }}>
            {splitTab === 'settings' && (
              <Box sx={{ p: 2 }}>
                {/* 전략 설정 */}
                <Box sx={{ mb: 3 }}>
                  <Typography sx={{ fontSize: '11px', color: themeStyle.textSecondaryColor, mb: 0.75 }}>
                    종목
                  </Typography>
                  <CryptoNameComboBox
                    value={symbol}
                    onChange={handleCryptoChange}
                    disabled={loading}
                  />
                </Box>

                {/* 정배열 전략 */}
                <Box sx={{ mb: 3 }}>
                  <Typography sx={{ fontSize: '11px', color: themeStyle.textSecondaryColor, mb: 0.75, display: 'flex', alignItems: 'center', gap: 0.5 }}>
                    <TrendingUp sx={{ fontSize: 12, color: '#22c55e' }} />
                    정배열 전략
                  </Typography>
                  <FormControl fullWidth size="small">
                    <Select
                      value={uptrendStrategy}
                      onChange={(e) => setUptrendStrategy(e.target.value as number | '')}
                      disabled={loading}
                      displayEmpty
                      sx={{ bgcolor: themeStyle.backgroundColor }}
                    >
                      <MenuItem value="">선택안함</MenuItem>
                      {uptrendRules.map((r) => (
                        <MenuItem key={r.id} value={r.id}>{r.name}</MenuItem>
                      ))}
                    </Select>
                  </FormControl>
                </Box>

                {/* 역배열 전략 */}
                <Box sx={{ mb: 3 }}>
                  <Typography sx={{ fontSize: '11px', color: themeStyle.textSecondaryColor, mb: 0.75, display: 'flex', alignItems: 'center', gap: 0.5 }}>
                    <TrendingDown sx={{ fontSize: 12, color: '#ef4444' }} />
                    역배열 전략
                  </Typography>
                  <FormControl fullWidth size="small">
                    <Select
                      value={downtrendStrategy}
                      onChange={(e) => setDowntrendStrategy(e.target.value as number | '')}
                      disabled={loading}
                      displayEmpty
                      sx={{ bgcolor: themeStyle.backgroundColor }}
                    >
                      <MenuItem value="">선택안함</MenuItem>
                      {downtrendRules.map((r) => (
                        <MenuItem key={r.id} value={r.id}>{r.name}</MenuItem>
                      ))}
                    </Select>
                  </FormControl>
                </Box>

                <Box sx={{ mb: 3 }}>
                  <Typography sx={{ fontSize: '11px', color: themeStyle.textSecondaryColor, mb: 0.75 }}>
                    분석 기간
                  </Typography>
                  <FormControl fullWidth size="small">
                    <Select
                      value={period}
                      onChange={(e) => handlePeriodChange(e.target.value)}
                      disabled={loading}
                      sx={{ bgcolor: themeStyle.backgroundColor }}
                    >
                      <MenuItem value="1day">1일</MenuItem>
                      <MenuItem value="1week">1주일</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>
                </Box>

                <Box sx={{ mb: 3 }}>
                  <Typography sx={{ fontSize: '11px', color: themeStyle.textSecondaryColor, mb: 0.75 }}>
                    초기 투자금
                  </Typography>
                  <TextField
                    fullWidth
                    size="small"
                    type="number"
                    value={initialCapital}
                    onChange={(e) => setInitialCapital(Number(e.target.value))}
                    disabled={loading}
                    InputProps={{
                      endAdornment: <InputAdornment position="end">원</InputAdornment>,
                    }}
                    sx={{ bgcolor: themeStyle.backgroundColor }}
                  />
                </Box>

                <Button
                  fullWidth
                  variant="contained"
                  startIcon={loading ? <CircularProgress size={16} color="inherit" /> : <PlayArrow />}
                  onClick={handleRunBacktest}
                  disabled={loading || (!uptrendStrategy && !downtrendStrategy)}
                  sx={{ 
                    bgcolor: themeStyle.primaryColor,
                    borderRadius: `${themeStyle.cardBorderRadius}px`,
                    py: 1.5,
                    '&:hover': { bgcolor: themeStyle.accentColor },
                  }}
                >
                  {loading ? '분석 중...' : '투자실행'}
                </Button>
              </Box>
            )}

            {splitTab === 'results' && (
              <Box sx={{ p: 2 }}>
                {/* 메트릭 카드 */}
                <Box sx={{ 
                  display: 'grid', 
                  gridTemplateColumns: '1fr 1fr',
                  gap: 2,
                  mb: 3,
                }}>
                  {/* 수익률 */}
                  <Card sx={{ 
                    bgcolor: themeStyle.backgroundColor,
                    borderRadius: `${themeStyle.cardBorderRadius}px`,
                    border: `1px solid ${themeStyle.borderColor}`,
                  }}>
                    <CardContent sx={{ p: 2 }}>
                      <Typography variant="caption" sx={{ color: themeStyle.textSecondaryColor }}>
                        수익률
                      </Typography>
                      <Typography variant="h5" sx={{ 
                        fontWeight: 700, 
                        color: isProfit ? '#22c55e' : '#ef4444',
                      }}>
                        {isProfit ? '+' : ''}{returnRate.toFixed(2)}%
                      </Typography>
                    </CardContent>
                  </Card>

                  {/* 순이익 */}
                  <Card sx={{ 
                    bgcolor: themeStyle.backgroundColor,
                    borderRadius: `${themeStyle.cardBorderRadius}px`,
                    border: `1px solid ${themeStyle.borderColor}`,
                  }}>
                    <CardContent sx={{ p: 2 }}>
                      <Typography variant="caption" sx={{ color: themeStyle.textSecondaryColor }}>
                        순이익
                      </Typography>
                      <Typography variant="h6" sx={{ 
                        fontWeight: 700, 
                        color: isProfit ? '#22c55e' : '#ef4444',
                      }}>
                        {netProfit >= 0 ? '+' : ''}{(netProfit / 10000).toFixed(1)}만원
                      </Typography>
                    </CardContent>
                  </Card>

                  {/* 승률 */}
                  <Card sx={{ 
                    bgcolor: themeStyle.backgroundColor,
                    borderRadius: `${themeStyle.cardBorderRadius}px`,
                    border: `1px solid ${themeStyle.borderColor}`,
                  }}>
                    <CardContent sx={{ p: 2 }}>
                      <Typography variant="caption" sx={{ color: themeStyle.textSecondaryColor }}>
                        승률
                      </Typography>
                      <Typography variant="h6" sx={{ 
                        fontWeight: 700, 
                        color: themeStyle.primaryColor,
                      }}>
                        {accuracy.overall.toFixed(1)}%
                      </Typography>
                    </CardContent>
                  </Card>

                  {/* 거래 수 */}
                  <Card sx={{ 
                    bgcolor: themeStyle.backgroundColor,
                    borderRadius: `${themeStyle.cardBorderRadius}px`,
                    border: `1px solid ${themeStyle.borderColor}`,
                  }}>
                    <CardContent sx={{ p: 2 }}>
                      <Typography variant="caption" sx={{ color: themeStyle.textSecondaryColor }}>
                        거래 수
                      </Typography>
                      <Typography variant="h6" sx={{ 
                        fontWeight: 700, 
                        color: themeStyle.textColor,
                      }}>
                        {displayTotalTrades}회
                      </Typography>
                    </CardContent>
                  </Card>
                </Box>

                {/* 상세 정보 */}
                {result && (
                  <Card sx={{ 
                    bgcolor: themeStyle.backgroundColor,
                    borderRadius: `${themeStyle.cardBorderRadius}px`,
                    border: `1px solid ${themeStyle.borderColor}`,
                  }}>
                    <CardContent sx={{ p: 2 }}>
                      <Typography variant="subtitle2" sx={{ color: themeStyle.textColor, mb: 2, fontWeight: 600 }}>
                        상세 정보
                      </Typography>
                      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
                        <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                          <Typography variant="body2" sx={{ color: themeStyle.textSecondaryColor }}>초기 투자금</Typography>
                          <Typography variant="body2" sx={{ color: themeStyle.textColor }}>{initialCapital.toLocaleString()}원</Typography>
                        </Box>
                        <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                          <Typography variant="body2" sx={{ color: themeStyle.textSecondaryColor }}>최종 자산</Typography>
                          <Typography variant="body2" sx={{ color: themeStyle.textColor }}>{result.finalCapital.toLocaleString()}원</Typography>
                        </Box>
                        <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                          <Typography variant="body2" sx={{ color: themeStyle.textSecondaryColor }}>최대 수익</Typography>
                          <Typography variant="body2" sx={{ color: '#22c55e' }}>{(result.maxProfit ?? 0).toLocaleString()}원</Typography>
                        </Box>
                        <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                          <Typography variant="body2" sx={{ color: themeStyle.textSecondaryColor }}>최대 손실</Typography>
                          <Typography variant="body2" sx={{ color: '#ef4444' }}>{(result.maxLoss ?? 0).toLocaleString()}원</Typography>
                        </Box>
                      </Box>
                    </CardContent>
                  </Card>
                )}
              </Box>
            )}
          </Box>
        </Box>

        {/* 오른쪽 패널: 차트 */}
        <Box sx={{ 
          display: 'flex',
          flexDirection: 'column',
          minHeight: 0, // flex 자식 요소의 스크롤 작동을 위해 필요
          overflow: 'hidden',
          bgcolor: themeStyle.backgroundColor,
        }}>
          {/* 차트 헤더 */}
          <Box sx={{ 
            p: 2, 
            borderBottom: `1px solid ${themeStyle.borderColor}`,
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            bgcolor: themeStyle.surfaceColor,
          }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
              <Typography variant="h6" sx={{ fontWeight: 600, color: themeStyle.textColor }}>
                {symbol}
              </Typography>
              <Chip 
                label={currentPrice?.toLocaleString() + '원'} 
                size="small"
                sx={{ 
                  bgcolor: isProfit ? 'rgba(34,197,94,0.2)' : 'rgba(239,68,68,0.2)',
                  color: isProfit ? '#22c55e' : '#ef4444',
                  fontWeight: 600,
                }}
              />
              <Chip 
                label={`${isProfit ? '+' : ''}${priceChange.toFixed(2)}%`}
                size="small"
                sx={{ 
                  bgcolor: isProfit ? 'rgba(34,197,94,0.1)' : 'rgba(239,68,68,0.1)',
                  color: isProfit ? '#22c55e' : '#ef4444',
                }}
              />
            </Box>
            <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>
              {/* 시간프레임 선택 */}
              <FormControl size="small" sx={{ minWidth: 80 }}>
                <Select
                  value={timeframe}
                  onChange={(e) => handleIntervalChange(e.target.value)}
                  sx={{ 
                    bgcolor: themeStyle.backgroundColor,
                    color: themeStyle.textColor,
                    '& .MuiSelect-icon': { color: themeStyle.textSecondaryColor },
                  }}
                >
                  <MenuItem value="1m">1분</MenuItem>
                  <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">1일</MenuItem>
                </Select>
              </FormControl>
              <IconButton 
                size="small" 
                onClick={handlePreviousPeriod}
                disabled={loading || isPeriodLoading || !canGoPrevious()}
                sx={{ color: themeStyle.textSecondaryColor }}
              >
                <ChevronLeft />
              </IconButton>
              <IconButton 
                size="small" 
                onClick={handleNextPeriod}
                disabled={loading || isPeriodLoading || !canGoNext()}
                sx={{ color: themeStyle.textSecondaryColor }}
              >
                <ChevronRight />
              </IconButton>
            </Box>
          </Box>

          {/* 차트 영역 */}
          <Box sx={{ 
            flex: 1, 
            overflow: 'auto',
            minHeight: 0, // flex 자식 요소의 스크롤 작동을 위해 필요
            WebkitOverflowScrolling: 'touch',
          }}>
            {loading ? (
              <Box sx={{ 
                  display: 'flex', 
                  alignItems: 'center', 
                  justifyContent: 'center', 
                height: '100%',
                flexDirection: 'column',
                gap: 2,
              }}>
                <CircularProgress sx={{ color: themeStyle.primaryColor }} />
                <Typography sx={{ color: themeStyle.textSecondaryColor }}>분석 중...</Typography>
              </Box>
            ) : error ? (
              <Box sx={{ 
                display: 'flex', 
                alignItems: 'center', 
                justifyContent: 'center', 
                height: '100%',
              }}>
                <Typography sx={{ color: '#ef4444' }}>{error}</Typography>
              </Box>
            ) : result ? (
              <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column', gap: 0 }}>
                {/* 캔들스틱 차트 */}
                <Box sx={{ flexGrow: 1, minHeight: 400 }}>
                  <CandlestickChart
                    ref={chartRef}
                    data={chartData}
                    indicatorData={result.indicatorData || []}
                    height={400}
                    onCrosshairMove={handleCandleChartCrosshairMove}
                    externalHoverTime={sharedHoverTime}
                    hideNativeCrosshair={true}
                    showTooltip={true}
                    onMarkerClick={(timestamp, tradeType) => handleMarkerClick(timestamp, tradeType as 'BUY' | 'SELL')}
                  />
                </Box>
                
                {/* 보조지표 차트들 - 차트테스트와 동일한 구성 */}
                {indicatorVisibility.settings.volume && (
                  <Box sx={{ height: 120 }}>
                    <IndicatorChart
                      ref={volumeChartRef}
                      type="volume"
                      data={result.indicatorData || []}
                      height={120}
                      title="거래량"
                      onCrosshairMove={handleIndicatorCrosshairMove}
                      externalHoverTime={sharedHoverTime}
                      hideNativeCrosshair={false}
                      hideTimeScale={false}
                    />
                  </Box>
                )}
                
                {indicatorVisibility.settings.newPsychological && (
                  <Box sx={{ height: 150 }}>
                    <IndicatorChart
                      ref={newPsychologicalChartRef}
                      type="newPsychological"
                      data={result.indicatorData || []}
                      height={150}
                      title="신심리도"
                      onCrosshairMove={handleIndicatorCrosshairMove}
                      externalHoverTime={sharedHoverTime}
                      hideNativeCrosshair={false}
                      hideTimeScale={false}
                    />
                  </Box>
                )}
                
                {indicatorVisibility.settings.investPsychological && (
                  <Box sx={{ height: 150 }}>
                    <IndicatorChart
                      ref={investPsychologicalChartRef}
                      type="investPsychological"
                      data={result.indicatorData || []}
                      height={150}
                      title="투자심리도"
                      onCrosshairMove={handleIndicatorCrosshairMove}
                      externalHoverTime={sharedHoverTime}
                      hideNativeCrosshair={false}
                      hideTimeScale={false}
                    />
                  </Box>
                )}
                
                {indicatorVisibility.settings.macdLine && (
                  <Box sx={{ height: 150 }}>
                    <IndicatorChart
                      ref={macdChartRef}
                      type="macd"
                      data={result.indicatorData || []}
                      height={150}
                      title="MACD"
                      onCrosshairMove={handleIndicatorCrosshairMove}
                      externalHoverTime={sharedHoverTime}
                      hideNativeCrosshair={false}
                      hideTimeScale={false}
                    />
                  </Box>
                )}
                
                {indicatorVisibility.settings.cci && (
                  <Box sx={{ height: 150 }}>
                    <IndicatorChart
                      ref={cciChartRef}
                      type="cci"
                      data={result.indicatorData || []}
                      height={150}
                      title="CCI"
                      onCrosshairMove={handleIndicatorCrosshairMove}
                      externalHoverTime={sharedHoverTime}
                      hideNativeCrosshair={false}
                      hideTimeScale={false}
                    />
                  </Box>
                )}
                
                {indicatorVisibility.settings.adx && (
                  <Box sx={{ height: 150 }}>
                    <IndicatorChart
                      ref={adxChartRef}
                      type="adx"
                      data={result.indicatorData || []}
                      height={150}
                      title="ADX"
                      onCrosshairMove={handleIndicatorCrosshairMove}
                      externalHoverTime={sharedHoverTime}
                      hideNativeCrosshair={false}
                      hideTimeScale={false}
                    />
                  </Box>
                )}
                
                {indicatorVisibility.settings.bwi && (
                  <Box sx={{ height: 150 }}>
                    <IndicatorChart
                      ref={bwiChartRef}
                      type="bwi"
                      data={result.indicatorData || []}
                      height={150}
                      title="BWI"
                      onCrosshairMove={handleIndicatorCrosshairMove}
                      externalHoverTime={sharedHoverTime}
                      hideNativeCrosshair={false}
                      hideTimeScale={false}
                    />
                  </Box>
                )}
                
                {indicatorVisibility.settings.plusDi && (
                  <Box sx={{ height: 150 }}>
                    <IndicatorChart
                      ref={dmiChartRef}
                      type="dmi"
                      data={result.indicatorData || []}
                      height={150}
                      title="DMI"
                      onCrosshairMove={handleIndicatorCrosshairMove}
                      externalHoverTime={sharedHoverTime}
                      hideNativeCrosshair={false}
                      hideTimeScale={false}
                    />
                  </Box>
                )}
                
                {indicatorVisibility.settings.obv && (
                  <Box sx={{ height: 150 }}>
                    <IndicatorChart
                      ref={obvChartRef}
                      type="obv"
                      data={result.indicatorData || []}
                      height={150}
                      title="OBV"
                      onCrosshairMove={handleIndicatorCrosshairMove}
                      externalHoverTime={sharedHoverTime}
                      hideNativeCrosshair={false}
                      hideTimeScale={false}
                    />
                  </Box>
                )}
                
                {indicatorVisibility.settings.rsi && (
                  <Box sx={{ height: 150 }}>
                    <IndicatorChart
                      ref={rsiChartRef}
                      type="rsi"
                      data={result.indicatorData || []}
                      height={150}
                      title="RSI"
                      onCrosshairMove={handleIndicatorCrosshairMove}
                      externalHoverTime={sharedHoverTime}
                      hideNativeCrosshair={false}
                      hideTimeScale={false}
                    />
                  </Box>
                )}
                
                {indicatorVisibility.settings.stochasticSlow && (
                  <Box sx={{ height: 150 }}>
                    <IndicatorChart
                      ref={stochasticChartRef}
                      type="stochastic"
                      data={result.indicatorData || []}
                      height={150}
                      title="Stochastic Slow"
                      onCrosshairMove={handleIndicatorCrosshairMove}
                      externalHoverTime={sharedHoverTime}
                      hideNativeCrosshair={false}
                      hideTimeScale={false}
                    />
                  </Box>
                )}
                
                {indicatorVisibility.settings.williamsR && (
                  <Box sx={{ height: 150 }}>
                    <IndicatorChart
                      ref={williamsRChartRef}
                      type="williamsR"
                      data={result.indicatorData || []}
                      height={150}
                      title="Williams %R"
                      onCrosshairMove={handleIndicatorCrosshairMove}
                      externalHoverTime={sharedHoverTime}
                      hideNativeCrosshair={false}
                      hideTimeScale={false}
                    />
                  </Box>
                )}
                
                {indicatorVisibility.settings.trix && (
                  <Box sx={{ height: 150 }}>
                    <IndicatorChart
                      ref={trixChartRef}
                      type="trix"
                      data={result.indicatorData || []}
                      height={150}
                      title="TRIX"
                      onCrosshairMove={handleIndicatorCrosshairMove}
                      externalHoverTime={sharedHoverTime}
                      hideNativeCrosshair={false}
                      hideTimeScale={false}
                    />
                  </Box>
                )}
                
                {indicatorVisibility.settings.volumeOsc && (
                  <Box sx={{ height: 150 }}>
                    <IndicatorChart
                      ref={volumeOscChartRef}
                      type="volumeOsc"
                      data={result.indicatorData || []}
                      height={150}
                      title="VolumeOSC"
                      onCrosshairMove={handleIndicatorCrosshairMove}
                      externalHoverTime={sharedHoverTime}
                      hideNativeCrosshair={false}
                      hideTimeScale={false}
                    />
                  </Box>
                )}
                
                {indicatorVisibility.settings.vr && (
                  <Box sx={{ height: 150 }}>
                    <IndicatorChart
                      ref={vrChartRef}
                      type="vr"
                      data={result.indicatorData || []}
                      height={150}
                      title="VR"
                      onCrosshairMove={handleIndicatorCrosshairMove}
                      externalHoverTime={sharedHoverTime}
                      hideNativeCrosshair={false}
                      hideTimeScale={false}
                    />
                  </Box>
                )}
                
                {indicatorVisibility.settings.disparity && (
                  <Box sx={{ height: 150 }}>
                    <IndicatorChart
                      ref={disparityChartRef}
                      type="disparity"
                      data={result.indicatorData || []}
                      height={150}
                      title="이격도"
                      onCrosshairMove={handleIndicatorCrosshairMove}
                      externalHoverTime={sharedHoverTime}
                      hideNativeCrosshair={false}
                      hideTimeScale={false}
                    />
                  </Box>
                )}
              </Box>
            ) : (
              <Box sx={{ 
                display: 'flex', 
                alignItems: 'center', 
                justifyContent: 'center', 
                height: '100%',
                flexDirection: 'column',
                gap: 2,
              }}>
                <Typography variant="h6" sx={{ color: themeStyle.textSecondaryColor }}>
                  📈 차트 영역
                </Typography>
                <Typography variant="body2" sx={{ color: themeStyle.textSecondaryColor }}>
                  전략을 선택하고 투자실행 버튼을 클릭하세요
                </Typography>
                </Box>
              )}
          </Box>
        </Box>
      </Box>
    );
  };

  // 미니멀 테마 (풀스크린 차트 + 플로팅 컨트롤)
  const MinimalLayout = () => (
                  <Box sx={{ 
      height: 'calc(100vh - 180px)',
      bgcolor: themeStyle.backgroundColor,
      mx: -3,
      my: -2,
      position: 'relative',
      overflow: 'hidden',
                  }}>
      {/* 풀스크린 차트 */}
      <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
        {renderChartHeader(true)}
        {renderChartArea('100%')}
                  </Box>

      {/* 플로팅 설정 버튼 */}
      <Fab 
        color="primary" 
        size="medium"
        onClick={() => setMobileSettingsOpen(true)}
        sx={{ 
          position: 'absolute', 
          bottom: 16, 
          left: 16,
          bgcolor: isDark ? '#27272a' : '#fff',
          color: isDark ? '#fff' : '#333',
          '&:hover': { bgcolor: isDark ? '#3f3f46' : '#f5f5f5' },
        }}
      >
        <SettingsIcon />
      </Fab>

      {/* 플로팅 결과 버튼 */}
      <Fab 
        color="secondary" 
        size="medium"
        onClick={() => setMobileResultsOpen(true)}
        sx={{ 
          position: 'absolute', 
          bottom: 16, 
          right: 16,
          bgcolor: isProfit ? 'rgba(34, 197, 94, 0.9)' : 'rgba(239, 68, 68, 0.9)',
        }}
      >
        {isProfit ? <TrendingUp /> : <TrendingDown />}
      </Fab>

      {/* 플로팅 수익률 표시 */}
      {result && (
        <Box sx={{
          position: 'absolute',
          top: 70,
          right: 16,
          bgcolor: isDark ? 'rgba(19, 19, 24, 0.9)' : 'rgba(255, 255, 255, 0.9)',
          borderRadius: 2,
          p: 1.5,
          boxShadow: 3,
        }}>
          <Typography sx={{ fontSize: '24px', fontWeight: 700, color: isProfit ? '#22c55e' : '#ef4444' }}>
            {isProfit ? '+' : ''}{returnRate.toFixed(2)}%
                    </Typography>
            </Box>
          )}

      {/* 설정 드로어 */}
      <Drawer
        anchor="left"
        open={mobileSettingsOpen}
        onClose={() => setMobileSettingsOpen(false)}
      >
        <Box sx={{ width: 300, bgcolor: themeStyle.surfaceColor, height: '100%' }}>
          <Box sx={{ 
            p: 2, 
            borderBottom: `1px solid ${themeStyle.borderColor}`,
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}>
            <Typography fontWeight={600}>전략 설정</Typography>
            <IconButton onClick={() => setMobileSettingsOpen(false)}>
              <CloseIcon />
            </IconButton>
        </Box>
          {settingsContent}
      </Box>
      </Drawer>

      {/* 결과 드로어 */}
      <Drawer
        anchor="right"
        open={mobileResultsOpen}
        onClose={() => setMobileResultsOpen(false)}
      >
        <Box sx={{ width: 320, bgcolor: themeStyle.surfaceColor, height: '100%' }}>
                <Box sx={{ 
            p: 2, 
            borderBottom: `1px solid ${themeStyle.borderColor}`,
                  display: 'flex', 
            justifyContent: 'space-between',
                  alignItems: 'center', 
                }}>
            <Typography fontWeight={600}>투자 결과</Typography>
            <IconButton onClick={() => setMobileResultsOpen(false)}>
              <CloseIcon />
            </IconButton>
                </Box>
          {resultsContent}
            </Box>
      </Drawer>
    </Box>
  );

  // 테마 ID에 따른 레이아웃 선택 (직접 함수 호출로 리렌더링 방지)
  const getLayoutForTheme = (themeId: UIThemeId): React.ReactNode => {
    // PC 테마
    if (themeId === 'pc-01-trading-terminal') {
      return isDesktop ? DefaultLayout() : CompactLayout();
    }
    if (themeId === 'pc-02-analytics-report') {
      return AnalyticsReportLayout();
    }
    if (themeId === 'pc-04-dark-pro') {
      return DarkProLayout();
    }
    if (themeId === 'pc-05-splitview') {
      return SplitViewLayout();
    }
    
    // 태블릿 테마
    if (themeId.startsWith('tablet-')) {
      if (themeId === 'tablet-01-grid-dashboard' || themeId === 'tablet-04-slide-panel') {
        return ModernLayout();
      }
      if (themeId === 'tablet-02-card-stack' || themeId === 'tablet-05-compact-pro') {
        return CompactLayout();
      }
      if (themeId === 'tablet-03-split-horizontal') {
        return CompactLayout();
      }
      return CompactLayout();
    }
    
    // 모바일 테마
    if (themeId.startsWith('mobile-')) {
      if (themeId === 'mobile-01-app-style' || themeId === 'mobile-05-minimal-dark') {
        return MinimalLayout();
      }
      if (themeId === 'mobile-02-card-scroll') {
        return CompactLayout();
      }
      if (themeId === 'mobile-03-fullscreen-chart') {
        return MinimalLayout();
      }
      if (themeId === 'mobile-04-bottom-sheet') {
        return CompactLayout();
      }
      return CompactLayout();
    }
    
    // 기본값
    return isDesktop ? DefaultLayout() : CompactLayout();
  };

  // 거래 상세 정보 다이얼로그
  const TradeDetailDialog = () => (
    <Dialog
      open={tradeDetailOpen}
      onClose={() => setTradeDetailOpen(false)}
      maxWidth="sm"
      fullWidth
      PaperProps={{
        sx: {
          bgcolor: isDark ? '#1a1b2e' : '#fff',
          color: isDark ? '#e0e0e0' : '#333',
          borderRadius: 2,
          border: isDark ? '1px solid rgba(80, 100, 160, 0.3)' : 'none',
        }
      }}
    >
      <DialogTitle sx={{ 
        display: 'flex', 
        alignItems: 'center', 
        justifyContent: 'space-between',
        borderBottom: `1px solid ${isDark ? '#27272a' : '#e0e0e0'}`,
        pb: 1.5,
      }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
          <Box sx={{ 
            fontSize: '24px',
            display: 'flex',
            alignItems: 'center',
          }}>
            {selectedTrade?.tradeType === 'BUY' ? '📈' : '📉'}
          </Box>
          <Box>
            <Typography variant="h6" sx={{ fontWeight: 600, fontSize: '16px' }}>
              {selectedTrade?.tradeType === 'BUY' ? '매수' : '매도'} 신호 상세
            </Typography>
            <Typography variant="caption" sx={{ color: isDark ? '#71717a' : '#999' }}>
              {selectedTrade?.timestamp}
            </Typography>
          </Box>
        </Box>
        <IconButton onClick={() => setTradeDetailOpen(false)} size="small">
          <CloseIcon />
        </IconButton>
      </DialogTitle>
      <DialogContent sx={{ pt: 2, maxHeight: '70vh', overflowY: 'auto' }}>
        {selectedTrade && (
          <Box>
            {/* 기본 거래 정보 */}
            <Box sx={{ 
              mb: 2, 
              p: 2, 
              bgcolor: isDark ? 'rgba(30, 35, 50, 0.7)' : '#f5f5f5',
              borderRadius: 1,
              border: isDark ? '1px solid rgba(80, 100, 160, 0.2)' : 'none',
            }}>
              <Typography sx={{ fontWeight: 600, mb: 1.5, fontSize: '13px', color: isDark ? '#a1a1aa' : '#666' }}>
                📊 거래 정보
              </Typography>
              <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 1.5 }}>
                <Box>
                  <Typography sx={{ fontSize: '11px', color: isDark ? '#71717a' : '#999' }}>체결가</Typography>
                  <Typography sx={{ fontWeight: 600, fontSize: '14px' }}>₩{selectedTrade.price?.toLocaleString()}</Typography>
                </Box>
                <Box>
                  <Typography sx={{ fontSize: '11px', color: isDark ? '#71717a' : '#999' }}>수량</Typography>
                  <Typography sx={{ fontWeight: 600, fontSize: '14px' }}>{selectedTrade.quantity?.toFixed(6)}</Typography>
                </Box>
                <Box>
                  <Typography sx={{ fontSize: '11px', color: isDark ? '#71717a' : '#999' }}>거래금액</Typography>
                  <Typography sx={{ fontWeight: 600, fontSize: '14px' }}>₩{selectedTrade.totalAmount?.toLocaleString()}</Typography>
                </Box>
                <Box>
                  <Typography sx={{ fontSize: '11px', color: isDark ? '#71717a' : '#999' }}>수수료</Typography>
                  <Typography sx={{ fontWeight: 600, fontSize: '14px' }}>₩{selectedTrade.commission?.toLocaleString()}</Typography>
                </Box>
                {selectedTrade.tradeType === 'SELL' && (
                  <>
                    <Box>
                      <Typography sx={{ fontSize: '11px', color: isDark ? '#71717a' : '#999' }}>손익</Typography>
                      <Typography sx={{ 
                        fontWeight: 600, 
                        fontSize: '14px',
                        color: (selectedTrade.profitLoss ?? 0) >= 0 ? '#22c55e' : '#ef4444',
                      }}>
                        {(selectedTrade.profitLoss ?? 0) >= 0 ? '+' : ''}₩{selectedTrade.profitLoss?.toLocaleString()}
                      </Typography>
                    </Box>
                    <Box>
                      <Typography sx={{ fontSize: '11px', color: isDark ? '#71717a' : '#999' }}>수익률</Typography>
                      <Typography sx={{ 
                        fontWeight: 600, 
                        fontSize: '14px',
                        color: (selectedTrade.returnRate ?? 0) >= 0 ? '#22c55e' : '#ef4444',
                      }}>
                        {(selectedTrade.returnRate ?? 0) >= 0 ? '+' : ''}{selectedTrade.returnRate?.toFixed(2)}%
                      </Typography>
                    </Box>
                  </>
                )}
              </Box>
            </Box>
            
            {/* 캔들 차트 정보 (OHLCV) */}
            {(selectedTrade.open || selectedTrade.high || selectedTrade.low || selectedTrade.close) && (
              <Box sx={{ 
                mb: 2, 
                p: 2, 
                bgcolor: isDark ? 'rgba(30, 35, 50, 0.7)' : '#f5f5f5',
                borderRadius: 1,
                border: isDark ? '1px solid rgba(80, 100, 160, 0.2)' : 'none',
              }}>
                <Typography sx={{ fontWeight: 600, mb: 1.5, fontSize: '13px', color: isDark ? '#a1a1aa' : '#666' }}>
                  🕯️ 해당 시점 캔들 정보
                </Typography>
                <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 1 }}>
                  <Box sx={{ textAlign: 'center', p: 1, bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff', borderRadius: 1 }}>
                    <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#999' }}>시가 (O)</Typography>
                    <Typography sx={{ fontWeight: 600, fontSize: '12px', color: isDark ? '#e0e0e0' : '#333' }}>
                      ₩{selectedTrade.open?.toLocaleString()}
                    </Typography>
                  </Box>
                  <Box sx={{ textAlign: 'center', p: 1, bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff', borderRadius: 1 }}>
                    <Typography sx={{ fontSize: '10px', color: '#ef4444' }}>고가 (H)</Typography>
                    <Typography sx={{ fontWeight: 600, fontSize: '12px', color: '#ef4444' }}>
                      ₩{selectedTrade.high?.toLocaleString()}
                    </Typography>
                  </Box>
                  <Box sx={{ textAlign: 'center', p: 1, bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff', borderRadius: 1 }}>
                    <Typography sx={{ fontSize: '10px', color: '#3b82f6' }}>저가 (L)</Typography>
                    <Typography sx={{ fontWeight: 600, fontSize: '12px', color: '#3b82f6' }}>
                      ₩{selectedTrade.low?.toLocaleString()}
                    </Typography>
                  </Box>
                  <Box sx={{ textAlign: 'center', p: 1, bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff', borderRadius: 1 }}>
                    <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#999' }}>종가 (C)</Typography>
                    <Typography sx={{ fontWeight: 600, fontSize: '12px', color: isDark ? '#e0e0e0' : '#333' }}>
                      ₩{selectedTrade.close?.toLocaleString()}
                    </Typography>
                  </Box>
                  <Box sx={{ textAlign: 'center', p: 1, bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff', borderRadius: 1 }}>
                    <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#999' }}>거래량</Typography>
                    <Typography sx={{ fontWeight: 600, fontSize: '12px', color: isDark ? '#e0e0e0' : '#333' }}>
                      {selectedTrade.volume?.toLocaleString(undefined, { maximumFractionDigits: 2 })}
                    </Typography>
                  </Box>
                </Box>
              </Box>
            )}
            
            {/* 주요 지표 스냅샷 */}
            {selectedTrade.indicators && (
              <Box sx={{ 
                mb: 2, 
                p: 2, 
                bgcolor: isDark ? 'rgba(30, 35, 50, 0.7)' : '#f5f5f5',
                borderRadius: 1,
                border: isDark ? '1px solid rgba(80, 100, 160, 0.2)' : 'none',
              }}>
                <Typography sx={{ fontWeight: 600, mb: 1.5, fontSize: '13px', color: isDark ? '#a1a1aa' : '#666' }}>
                  📈 해당 시점 주요 지표
                </Typography>
                <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 1.5 }}>
                  {/* 이동평균선 */}
                  <Box sx={{ p: 1.5, bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff', borderRadius: 1 }}>
                    <Typography sx={{ fontSize: '11px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 0.5 }}>이동평균선</Typography>
                    <Box sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#999' }}>
                      {selectedTrade.indicators.ma10 && <Box>MA10: ₩{selectedTrade.indicators.ma10.toLocaleString()}</Box>}
                      {selectedTrade.indicators.ma20 && <Box>MA20: ₩{selectedTrade.indicators.ma20.toLocaleString()}</Box>}
                      {selectedTrade.indicators.ma60 && <Box>MA60: ₩{selectedTrade.indicators.ma60.toLocaleString()}</Box>}
                    </Box>
                  </Box>
                  
                  {/* MACD */}
                  <Box sx={{ p: 1.5, bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff', borderRadius: 1 }}>
                    <Typography sx={{ fontSize: '11px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 0.5 }}>MACD</Typography>
                    <Box sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#999' }}>
                      {selectedTrade.indicators.macdLine !== undefined && <Box>MACD: {selectedTrade.indicators.macdLine?.toFixed(2)}</Box>}
                      {selectedTrade.indicators.macdSignal !== undefined && <Box>Signal: {selectedTrade.indicators.macdSignal?.toFixed(2)}</Box>}
                      {selectedTrade.indicators.macdHistogram !== undefined && (
                        <Box sx={{ color: (selectedTrade.indicators.macdHistogram ?? 0) >= 0 ? '#22c55e' : '#ef4444' }}>
                          Histogram: {selectedTrade.indicators.macdHistogram?.toFixed(2)}
                        </Box>
                      )}
                    </Box>
                  </Box>
                  
                  {/* Stochastic */}
                  <Box sx={{ p: 1.5, bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff', borderRadius: 1 }}>
                    <Typography sx={{ fontSize: '11px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 0.5 }}>Stochastic</Typography>
                    <Box sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#999' }}>
                      {selectedTrade.indicators.stochK !== undefined && <Box>%K: {selectedTrade.indicators.stochK?.toFixed(2)}</Box>}
                      {selectedTrade.indicators.stochD !== undefined && <Box>%D: {selectedTrade.indicators.stochD?.toFixed(2)}</Box>}
                    </Box>
                  </Box>
                  
                  {/* RSI */}
                  {selectedTrade.indicators.rsi !== undefined && (
                    <Box sx={{ p: 1.5, bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff', borderRadius: 1 }}>
                      <Typography sx={{ fontSize: '11px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 0.5 }}>RSI</Typography>
                      <Typography sx={{ 
                        fontSize: '14px', 
                        fontWeight: 600,
                        color: (selectedTrade.indicators.rsi ?? 50) > 70 ? '#ef4444' : (selectedTrade.indicators.rsi ?? 50) < 30 ? '#22c55e' : (isDark ? '#e0e0e0' : '#333')
                      }}>
                        {selectedTrade.indicators.rsi?.toFixed(2)}
                      </Typography>
                    </Box>
                  )}
                  
                  {/* ADX */}
                  {selectedTrade.indicators.adx !== undefined && (
                    <Box sx={{ p: 1.5, bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff', borderRadius: 1 }}>
                      <Typography sx={{ fontSize: '11px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 0.5 }}>ADX</Typography>
                      <Box sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#999' }}>
                        <Box>ADX: {selectedTrade.indicators.adx?.toFixed(2)}</Box>
                        {selectedTrade.indicators.plusDi !== undefined && <Box sx={{ color: '#22c55e' }}>+DI: {selectedTrade.indicators.plusDi?.toFixed(2)}</Box>}
                        {selectedTrade.indicators.minusDi !== undefined && <Box sx={{ color: '#ef4444' }}>-DI: {selectedTrade.indicators.minusDi?.toFixed(2)}</Box>}
                      </Box>
                    </Box>
                  )}
                  
                  {/* 일목균형표 */}
                  {(selectedTrade.indicators.ichimokuTenkan !== undefined || selectedTrade.indicators.ichimokuKijun !== undefined) && (
                    <Box sx={{ p: 1.5, bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff', borderRadius: 1 }}>
                      <Typography sx={{ fontSize: '11px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 0.5 }}>일목균형표</Typography>
                      <Box sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#999' }}>
                        {selectedTrade.indicators.ichimokuTenkan !== undefined && <Box>전환선: ₩{selectedTrade.indicators.ichimokuTenkan?.toLocaleString()}</Box>}
                        {selectedTrade.indicators.ichimokuKijun !== undefined && <Box>기준선: ₩{selectedTrade.indicators.ichimokuKijun?.toLocaleString()}</Box>}
                      </Box>
                    </Box>
                  )}
                </Box>
              </Box>
            )}
            
            {/* 적용 전략 정보 */}
            {selectedTrade.strategyName && (
              <Box sx={{ 
                mb: 2, 
                p: 2, 
                bgcolor: isDark ? 'rgba(30, 35, 50, 0.7)' : '#f5f5f5',
                borderRadius: 1,
                border: isDark ? '1px solid rgba(80, 100, 160, 0.2)' : 'none',
              }}>
                <Typography sx={{ fontWeight: 600, mb: 1.5, fontSize: '13px', color: isDark ? '#a1a1aa' : '#666' }}>
                  🎯 적용 전략
                </Typography>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Chip 
                    label={selectedTrade.strategyName} 
                    size="small" 
                    sx={{ 
                      bgcolor: isDark ? 'rgba(59, 130, 246, 0.2)' : 'rgba(59, 130, 246, 0.1)',
                      color: '#3b82f6',
                      fontWeight: 600,
                    }} 
                  />
                  {selectedTrade.trendStatus && (
                    <Chip 
                      label={selectedTrade.trendStatus} 
                      size="small" 
                      sx={{ 
                        bgcolor: selectedTrade.trendStatus?.includes('정배열') 
                          ? 'rgba(34, 197, 94, 0.2)' 
                          : selectedTrade.trendStatus?.includes('역배열')
                            ? 'rgba(239, 68, 68, 0.2)'
                            : 'rgba(168, 162, 158, 0.2)',
                        color: selectedTrade.trendStatus?.includes('정배열') 
                          ? '#22c55e' 
                          : selectedTrade.trendStatus?.includes('역배열')
                            ? '#ef4444'
                            : '#a8a29e',
                        fontWeight: 500,
                        fontSize: '11px',
                      }} 
                    />
                  )}
                </Box>
              </Box>
            )}
            
            {/* 충족 조건 목록 */}
            {selectedTrade.matchedConditions && selectedTrade.matchedConditions.length > 0 && (
              <Box sx={{ 
                p: 2, 
                bgcolor: isDark ? 'rgba(30, 35, 50, 0.7)' : '#f5f5f5',
                borderRadius: 1,
                border: isDark ? '1px solid rgba(80, 100, 160, 0.2)' : 'none',
              }}>
                <Typography sx={{ fontWeight: 600, mb: 1.5, fontSize: '13px', color: isDark ? '#a1a1aa' : '#666' }}>
                  ✅ 충족 조건 ({selectedTrade.matchedConditions.filter(c => c.matched).length}/{selectedTrade.matchedConditions.length})
                </Typography>
                {selectedTrade.matchedConditions.map((cond, idx) => (
                  <Box key={idx} sx={{ 
                    mb: 1.5,
                    p: 1.5, 
                    bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff',
                    borderRadius: 1,
                    border: `1px solid ${cond.matched ? (isDark ? 'rgba(34, 197, 94, 0.3)' : 'rgba(34, 197, 94, 0.5)') : (isDark ? 'rgba(239, 68, 68, 0.3)' : 'rgba(239, 68, 68, 0.5)')}`,
                    opacity: cond.matched ? 1 : 0.7,
                  }}>
                    {/* 조건 헤더 */}
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
                      <Typography sx={{ fontSize: '14px' }}>
                        {cond.matched ? '✅' : '❌'}
                      </Typography>
                      <Box sx={{ flex: 1 }}>
                        <Typography sx={{ fontSize: '13px', fontWeight: 600, color: isDark ? '#e0e0e0' : '#333' }}>
                          {cond.indicatorName || cond.conditionType}
                        </Typography>
                        <Typography sx={{ fontSize: '11px', color: isDark ? '#a1a1aa' : '#666' }}>
                          {cond.description}
                        </Typography>
                      </Box>
                    </Box>
                    
                    {/* 값 정보 */}
                    <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(100px, 1fr))', gap: 1, mb: 1 }}>
                      {cond.currentValue != null && (
                        <Box sx={{ p: 0.5, bgcolor: isDark ? 'rgba(30, 35, 50, 0.5)' : '#f5f5f5', borderRadius: 0.5 }}>
                          <Typography sx={{ fontSize: '9px', color: isDark ? '#71717a' : '#999' }}>현재값</Typography>
                          <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#e0e0e0' : '#333' }}>
                            {typeof cond.currentValue === 'number' ? cond.currentValue.toFixed(4) : cond.currentValue}
                          </Typography>
                        </Box>
                      )}
                      {cond.previousValue != null && (
                        <Box sx={{ p: 0.5, bgcolor: isDark ? 'rgba(30, 35, 50, 0.5)' : '#f5f5f5', borderRadius: 0.5 }}>
                          <Typography sx={{ fontSize: '9px', color: isDark ? '#71717a' : '#999' }}>이전값</Typography>
                          <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#e0e0e0' : '#333' }}>
                            {cond.previousValue.toFixed(4)}
                          </Typography>
                        </Box>
                      )}
                      {cond.targetValue != null && (
                        <Box sx={{ p: 0.5, bgcolor: isDark ? 'rgba(30, 35, 50, 0.5)' : '#f5f5f5', borderRadius: 0.5 }}>
                          <Typography sx={{ fontSize: '9px', color: isDark ? '#71717a' : '#999' }}>기준값</Typography>
                          <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#e0e0e0' : '#333' }}>
                            {cond.targetValue.toFixed(4)}
                          </Typography>
                        </Box>
                      )}
                      {cond.compareValue != null && (
                        <Box sx={{ p: 0.5, bgcolor: isDark ? 'rgba(30, 35, 50, 0.5)' : '#f5f5f5', borderRadius: 0.5 }}>
                          <Typography sx={{ fontSize: '9px', color: isDark ? '#71717a' : '#999' }}>비교값</Typography>
                          <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#e0e0e0' : '#333' }}>
                            {cond.compareValue.toFixed(4)}
                          </Typography>
                        </Box>
                      )}
                      {cond.secondaryValue != null && (
                        <Box sx={{ p: 0.5, bgcolor: isDark ? 'rgba(30, 35, 50, 0.5)' : '#f5f5f5', borderRadius: 0.5 }}>
                          <Typography sx={{ fontSize: '9px', color: isDark ? '#71717a' : '#999' }}>보조값</Typography>
                          <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#e0e0e0' : '#333' }}>
                            {cond.secondaryValue.toFixed(4)}
                          </Typography>
                        </Box>
                      )}
                    </Box>
                    
                    {/* 상세 설명 */}
                    {cond.detailDescription && (
                      <Box sx={{ 
                        mt: 1, 
                        p: 1, 
                        bgcolor: isDark ? 'rgba(30, 35, 50, 0.8)' : '#f0f0f0',
                        borderRadius: 0.5,
                        borderLeft: `3px solid ${cond.matched ? '#22c55e' : '#ef4444'}`,
                      }}>
                        <Typography sx={{ 
                          fontSize: '11px', 
                          color: isDark ? '#a1a1aa' : '#666',
                          whiteSpace: 'pre-wrap',
                          fontFamily: 'monospace',
                        }}>
                          {cond.detailDescription}
                        </Typography>
                      </Box>
                    )}
                  </Box>
                ))}
              </Box>
            )}
            
            {/* 조건 정보가 없을 때 */}
            {(!selectedTrade.matchedConditions || selectedTrade.matchedConditions.length === 0) && !selectedTrade.strategyName && (
              <Box sx={{ 
                p: 2, 
                textAlign: 'center',
                bgcolor: isDark ? 'rgba(30, 35, 50, 0.7)' : '#f5f5f5',
                borderRadius: 1,
              }}>
                <Typography sx={{ fontSize: '13px', color: isDark ? '#71717a' : '#999' }}>
                  기본 전략으로 생성된 신호입니다.
                  <br />
                  상세 조건 정보는 전략관리에서 설정한 규칙을 사용할 때 표시됩니다.
                </Typography>
              </Box>
            )}
            
            {/* 보조지표 차트 (조건에 해당하는 지표가 있을 때만 표시) */}
            {selectedTrade.matchedConditions && selectedTrade.matchedConditions.length > 0 && result?.indicatorData && (() => {
              // 거래 시점 찾기
              const tradeTimestamp = selectedTrade.timestamp;
              const tradeIndex = result.indicatorData.findIndex(ind => {
                if (ind.time === tradeTimestamp) return true;
                if (ind.time?.replace('T', ' ') === tradeTimestamp?.replace('T', ' ')) return true;
                return false;
              });
              
              if (tradeIndex < 0) return null;
              
              // 전후 5개 데이터 추출 (총 11개) - 더 집중된 뷰
              const startIdx = Math.max(0, tradeIndex - 5);
              const endIdx = Math.min(result.indicatorData.length, tradeIndex + 6);
              const chartRange = result.indicatorData.slice(startIdx, endIdx);
              
              // 조건에서 사용된 지표 타입 추출
              const usedIndicators = new Set<string>();
              selectedTrade.matchedConditions.forEach(cond => {
                const type = cond.conditionType?.toUpperCase();
                if (type?.includes('MACD') || type?.includes('HISTOGRAM')) usedIndicators.add('MACD');
                if (type?.includes('RSI')) usedIndicators.add('RSI');
                if (type?.includes('STOCHASTIC') || type?.includes('STOCH')) usedIndicators.add('STOCHASTIC');
                if (type?.includes('CCI')) usedIndicators.add('CCI');
                if (type?.includes('ADX') || type?.includes('DI')) usedIndicators.add('ADX');
                if (type?.includes('TRIX')) usedIndicators.add('TRIX');
              });
              
              if (usedIndicators.size === 0) return null;
              
              // 차트 데이터 포맷
              const formattedData = chartRange.map((ind, idx) => {
                const date = ind.time?.includes('T') 
                  ? ind.time.split('T')[1]?.substring(0, 5) || ind.time.split('T')[0]?.substring(5)
                  : ind.time?.substring(5) || '';
                return {
                  date,
                  fullTime: ind.time,
                  isTradePoint: startIdx + idx === tradeIndex,
                  // MACD
                  macdLine: ind.macdLine,
                  signalLine: ind.signalLine,
                  histogram: ind.histogram,
                  // RSI
                  rsi: ind.rsi,
                  // Stochastic
                  stochK: ind.stochK,
                  stochD: ind.stochD,
                  // CCI
                  cci: ind.cci,
                  // ADX
                  adx: ind.adx,
                  plusDI: ind.plusDI,
                  minusDI: ind.minusDI,
                  // TRIX
                  trix: ind.trix,
                  trixSignal: ind.trixSignal,
                };
              });
              
              const tradePointIndex = tradeIndex - startIdx;
              
              // 정사각형 차트 박스 스타일 - 팝업 전체 너비 활용
              const chartBoxStyle = {
                width: '100%',
                height: 350,
                bgcolor: isDark ? 'rgba(20, 25, 40, 0.8)' : '#fff',
                borderRadius: 2,
                p: 2,
                border: isDark ? '1px solid rgba(80, 100, 160, 0.3)' : '1px solid #e0e0e0',
                boxShadow: isDark ? '0 4px 12px rgba(0,0,0,0.3)' : '0 2px 8px rgba(0,0,0,0.1)',
              };
              
              // 마커 크기
              const markerSize = 6;
              
              return (
                <Box sx={{ 
                  mt: 2, 
                  p: 2, 
                  bgcolor: isDark ? 'rgba(30, 35, 50, 0.7)' : '#f5f5f5',
                  borderRadius: 1,
                  border: isDark ? '1px solid rgba(80, 100, 160, 0.2)' : 'none',
                }}>
                  <Typography sx={{ fontWeight: 600, mb: 1.5, fontSize: '13px', color: isDark ? '#a1a1aa' : '#666' }}>
                    📊 조건 관련 지표 차트 (거래 시점 집중)
                  </Typography>
                  
                  <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, alignItems: 'center' }}>
                    {/* MACD 차트 */}
                    {usedIndicators.has('MACD') && (
                      <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: '100%' }}>
                        <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 1 }}>MACD</Typography>
                        <Box sx={chartBoxStyle}>
                          <ResponsiveContainer width="100%" height="100%">
                            <ComposedChart data={formattedData} margin={{ top: 15, right: 15, bottom: 25, left: 15 }}>
                              <CartesianGrid stroke={isDark ? '#27272a' : '#e0e0e0'} strokeDasharray="3 3" />
                              <XAxis dataKey="date" tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} interval={0} angle={-45} textAnchor="end" height={35} />
                              <YAxis tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} width={45} />
                              <ReferenceLine y={0} stroke={isDark ? '#52525b' : '#ccc'} strokeDasharray="2 2" />
                              <Bar dataKey="histogram" barSize={18}>
                                {formattedData.map((entry, index) => (
                                  <Cell key={`cell-${index}`} fill={(entry.histogram ?? 0) >= 0 ? '#22c55e' : '#ef4444'} />
                                ))}
                              </Bar>
                              <Line type="monotone" dataKey="macdLine" stroke="#2196F3" strokeWidth={2} dot={{ r: 3 }} />
                              <Line type="monotone" dataKey="signalLine" stroke="#FF9800" strokeWidth={2} dot={{ r: 3 }} />
                              <ReferenceLine x={formattedData[tradePointIndex]?.date} stroke={selectedTrade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'} strokeWidth={2} />
                              {formattedData[tradePointIndex]?.macdLine != null && (
                                <ReferenceDot 
                                  x={formattedData[tradePointIndex]?.date} 
                                  y={formattedData[tradePointIndex]?.macdLine} 
                                  r={markerSize} 
                                  fill={selectedTrade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'} 
                                  stroke="#fff" 
                                  strokeWidth={1.5}
                                />
                              )}
                            </ComposedChart>
                          </ResponsiveContainer>
                        </Box>
                      </Box>
                    )}
                    
                    {/* RSI 차트 */}
                    {usedIndicators.has('RSI') && (
                      <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: '100%' }}>
                        <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 1 }}>RSI</Typography>
                        <Box sx={chartBoxStyle}>
                          <ResponsiveContainer width="100%" height="100%">
                            <LineChart data={formattedData} margin={{ top: 15, right: 15, bottom: 25, left: 15 }}>
                              <CartesianGrid stroke={isDark ? '#27272a' : '#e0e0e0'} strokeDasharray="3 3" />
                              <XAxis dataKey="date" tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} interval={0} angle={-45} textAnchor="end" height={35} />
                              <YAxis domain={[0, 100]} tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} width={35} ticks={[30, 50, 70]} />
                              <ReferenceLine y={70} stroke="#ef4444" strokeDasharray="3 3" strokeWidth={1.5} />
                              <ReferenceLine y={30} stroke="#22c55e" strokeDasharray="3 3" strokeWidth={1.5} />
                              <Line type="monotone" dataKey="rsi" stroke="#00BCD4" strokeWidth={2.5} dot={{ r: 4, fill: '#00BCD4' }} />
                              <ReferenceLine x={formattedData[tradePointIndex]?.date} stroke={selectedTrade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'} strokeWidth={2} />
                              {formattedData[tradePointIndex]?.rsi != null && (
                                <ReferenceDot 
                                  x={formattedData[tradePointIndex]?.date} 
                                  y={formattedData[tradePointIndex]?.rsi} 
                                  r={markerSize} 
                                  fill={selectedTrade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'} 
                                  stroke="#fff" 
                                  strokeWidth={1.5}
                                />
                              )}
                            </LineChart>
                          </ResponsiveContainer>
                        </Box>
                      </Box>
                    )}
                    
                    {/* Stochastic 차트 */}
                    {usedIndicators.has('STOCHASTIC') && (
                      <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: '100%' }}>
                        <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 1 }}>Stochastic</Typography>
                        <Box sx={chartBoxStyle}>
                          <ResponsiveContainer width="100%" height="100%">
                            <LineChart data={formattedData} margin={{ top: 15, right: 15, bottom: 25, left: 15 }}>
                              <CartesianGrid stroke={isDark ? '#27272a' : '#e0e0e0'} strokeDasharray="3 3" />
                              <XAxis dataKey="date" tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} interval={0} angle={-45} textAnchor="end" height={35} />
                              <YAxis domain={[0, 100]} tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} width={35} ticks={[20, 50, 80]} />
                              <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="stochK" stroke="#FF9500" strokeWidth={2.5} dot={{ r: 4, fill: '#FF9500' }} name="%K" />
                              <Line type="monotone" dataKey="stochD" stroke="#2196F3" strokeWidth={2} dot={{ r: 3, fill: '#2196F3' }} name="%D" />
                              <ReferenceLine x={formattedData[tradePointIndex]?.date} stroke={selectedTrade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'} strokeWidth={2} />
                              {formattedData[tradePointIndex]?.stochK != null && (
                                <ReferenceDot 
                                  x={formattedData[tradePointIndex]?.date} 
                                  y={formattedData[tradePointIndex]?.stochK} 
                                  r={markerSize} 
                                  fill={selectedTrade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'} 
                                  stroke="#fff" 
                                  strokeWidth={1.5}
                                />
                              )}
                            </LineChart>
                          </ResponsiveContainer>
                        </Box>
                      </Box>
                    )}
                    
                    {/* CCI 차트 */}
                    {usedIndicators.has('CCI') && (
                      <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: '100%' }}>
                        <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 1 }}>CCI</Typography>
                        <Box sx={chartBoxStyle}>
                          <ResponsiveContainer width="100%" height="100%">
                            <LineChart data={formattedData} margin={{ top: 15, right: 15, bottom: 25, left: 15 }}>
                              <CartesianGrid stroke={isDark ? '#27272a' : '#e0e0e0'} strokeDasharray="3 3" />
                              <XAxis dataKey="date" tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} interval={0} angle={-45} textAnchor="end" height={35} />
                              <YAxis tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} width={45} />
                              <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={isDark ? '#52525b' : '#ccc'} strokeDasharray="2 2" />
                              <Line type="monotone" dataKey="cci" stroke="#9C27B0" strokeWidth={2.5} dot={{ r: 4, fill: '#9C27B0' }} />
                              <ReferenceLine x={formattedData[tradePointIndex]?.date} stroke={selectedTrade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'} strokeWidth={2} />
                              {formattedData[tradePointIndex]?.cci != null && (
                                <ReferenceDot 
                                  x={formattedData[tradePointIndex]?.date} 
                                  y={formattedData[tradePointIndex]?.cci} 
                                  r={markerSize} 
                                  fill={selectedTrade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'} 
                                  stroke="#fff" 
                                  strokeWidth={1.5}
                                />
                              )}
                            </LineChart>
                          </ResponsiveContainer>
                        </Box>
                      </Box>
                    )}
                    
                    {/* ADX 차트 */}
                    {usedIndicators.has('ADX') && (
                      <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: '100%' }}>
                        <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 1 }}>ADX / DI</Typography>
                        <Box sx={chartBoxStyle}>
                          <ResponsiveContainer width="100%" height="100%">
                            <LineChart data={formattedData} margin={{ top: 15, right: 15, bottom: 25, left: 15 }}>
                              <CartesianGrid stroke={isDark ? '#27272a' : '#e0e0e0'} strokeDasharray="3 3" />
                              <XAxis dataKey="date" tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} interval={0} angle={-45} textAnchor="end" height={35} />
                              <YAxis domain={[0, 'auto']} tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} width={35} />
                              <Line type="monotone" dataKey="adx" stroke="#FFD700" strokeWidth={2.5} dot={{ r: 4, fill: '#FFD700' }} name="ADX" />
                              <Line type="monotone" dataKey="plusDI" stroke="#22c55e" strokeWidth={2} dot={{ r: 3 }} name="+DI" />
                              <Line type="monotone" dataKey="minusDI" stroke="#ef4444" strokeWidth={2} dot={{ r: 3 }} name="-DI" />
                              <ReferenceLine x={formattedData[tradePointIndex]?.date} stroke={selectedTrade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'} strokeWidth={2} />
                              {formattedData[tradePointIndex]?.adx != null && (
                                <ReferenceDot 
                                  x={formattedData[tradePointIndex]?.date} 
                                  y={formattedData[tradePointIndex]?.adx} 
                                  r={markerSize} 
                                  fill={selectedTrade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'} 
                                  stroke="#fff" 
                                  strokeWidth={1.5}
                                />
                              )}
                            </LineChart>
                          </ResponsiveContainer>
                        </Box>
                      </Box>
                    )}
                    
                    {/* TRIX 차트 */}
                    {usedIndicators.has('TRIX') && (
                      <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: '100%' }}>
                        <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 1 }}>TRIX</Typography>
                        <Box sx={chartBoxStyle}>
                          <ResponsiveContainer width="100%" height="100%">
                            <LineChart data={formattedData} margin={{ top: 15, right: 15, bottom: 25, left: 15 }}>
                              <CartesianGrid stroke={isDark ? '#27272a' : '#e0e0e0'} strokeDasharray="3 3" />
                              <XAxis dataKey="date" tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} interval={0} angle={-45} textAnchor="end" height={35} />
                              <YAxis tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} width={45} />
                              <ReferenceLine y={0} stroke={isDark ? '#52525b' : '#ccc'} strokeDasharray="2 2" />
                              <Line type="monotone" dataKey="trix" stroke="#E91E63" strokeWidth={2.5} dot={{ r: 4, fill: '#E91E63' }} name="TRIX" />
                              <Line type="monotone" dataKey="trixSignal" stroke="#9C27B0" strokeWidth={2} dot={{ r: 3, fill: '#9C27B0' }} name="Signal" />
                              <ReferenceLine x={formattedData[tradePointIndex]?.date} stroke={selectedTrade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'} strokeWidth={2} />
                              {formattedData[tradePointIndex]?.trix != null && (
                                <ReferenceDot 
                                  x={formattedData[tradePointIndex]?.date} 
                                  y={formattedData[tradePointIndex]?.trix} 
                                  r={markerSize} 
                                  fill={selectedTrade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'} 
                                  stroke="#fff" 
                                  strokeWidth={1.5}
                                />
                              )}
                            </LineChart>
                          </ResponsiveContainer>
                        </Box>
                      </Box>
                    )}
                  </Box>
                  
                  <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 2, mt: 1.5 }}>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                      <Box sx={{ width: 10, height: 10, borderRadius: '50%', bgcolor: selectedTrade.tradeType === 'BUY' ? '#22c55e' : '#ef4444', border: '1.5px solid #fff' }} />
                      <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>
                        {selectedTrade.tradeType === 'BUY' ? '매수' : '매도'} 시점
                      </Typography>
                    </Box>
                    <Typography sx={{ fontSize: '10px', color: isDark ? '#52525b' : '#999' }}>
                      | 차트 범위: 전후 5개 캔들
                    </Typography>
                  </Box>
                </Box>
              );
            })()}
          </Box>
        )}
      </DialogContent>
      <DialogActions sx={{ borderTop: `1px solid ${isDark ? '#27272a' : '#e0e0e0'}`, pt: 1.5, pb: 1.5 }}>
        <Button onClick={() => setTradeDetailOpen(false)} variant="outlined" size="small">
          닫기
        </Button>
      </DialogActions>
    </Dialog>
  );

  return (
    <Grid container spacing={2}>
      {/* 상단 툴바 카드 */}
      <Grid item xs={12}>
        <Paper elevation={3} sx={{ p: 2 }}>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 2 }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
              <PlayArrow sx={{ fontSize: 24, color: '#22c55e' }} />
              <Typography variant="h6" sx={{ fontWeight: 600 }}>
                모의투자
              </Typography>
              <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                {symbol}
              </Typography>
              {result && (
                <Chip 
                  label={`${displayReturnRate >= 0 ? '+' : ''}${displayReturnRate.toFixed(2)}%`}
                  size="small"
                  color={displayReturnRate >= 0 ? 'success' : 'error'}
                />
              )}
            </Box>
            <Box sx={{ display: 'flex', gap: 1, alignItems: 'center', flexWrap: 'wrap' }}>
              {/* 종목 선택 */}
              <Box sx={{ minWidth: 150 }}>
                <CryptoNameComboBox
                  value={symbol}
                  onChange={handleCryptoChange}
                  disabled={loading}
                  label=""
                  placeholder="종목 선택"
                  size="small"
                />
              </Box>
              {/* 기간 선택 */}
              <FormControl size="small" sx={{ minWidth: 90 }}>
                <Select
                  value={period}
                  onChange={(e) => handlePeriodChange(e.target.value)}
                  disabled={loading}
                  sx={{ fontSize: '12px' }}
                >
                  <MenuItem value="1day">1일</MenuItem>
                  <MenuItem value="1week">1주일</MenuItem>
                  <MenuItem value="10days">10일</MenuItem>
                  <MenuItem value="1month">1개월</MenuItem>
                  <MenuItem value="3months">3개월</MenuItem>
                </Select>
              </FormControl>
              {/* 시간봉 선택 */}
              <FormControl size="small" sx={{ minWidth: 90 }}>
                <Select
                  value={timeframe}
                  onChange={(e) => setTimeframe(e.target.value)}
                  disabled={loading}
                  sx={{ fontSize: '12px' }}
                >
                  <MenuItem value="1m">1분봉</MenuItem>
                  <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>
                </Select>
              </FormControl>
              <Button
                variant="contained"
                size="small"
                startIcon={loading ? <CircularProgress size={14} color="inherit" /> : <PlayArrow />}
                onClick={handleRunBacktest}
                disabled={loading || (!uptrendStrategy && !downtrendStrategy)}
                sx={{
                  background: 'linear-gradient(135deg, #22c55e 0%, #16a34a 100%)',
                }}
              >
                {loading ? '실행 중...' : '투자실행'}
              </Button>
            </Box>
          </Box>
        </Paper>
      </Grid>
      
      {/* 메인 콘텐츠 */}
      <Grid item xs={12}>
        <Paper elevation={2} sx={{ 
          overflow: 'hidden',
          // DefaultLayout 등 내부 레이아웃이 Paper 안에 표시되도록 함
        }}>
          {getLayoutForTheme(currentThemeId)}
        </Paper>
      </Grid>
      
      <TradeDetailDialog />
    </Grid>
  );
};

export default SimulationPage;
