import React, { useState, useEffect, useMemo, useRef } from 'react';
import {
  Box,
  AppBar,
  Toolbar,
  Typography,
  IconButton,
  Select,
  MenuItem,
  FormControl,
  CircularProgress,
  Alert,
  Drawer,
  Button,
  Divider,
  List,
  ListItem,
  ListItemText,
  ListItemSecondaryAction,
  Switch,
  Chip,
  Autocomplete,
  TextField,
  Fab,
} from '@mui/material';
import { 
  Refresh as RefreshIcon, 
  Settings as SettingsIcon,
  Menu as MenuIcon,
  Fullscreen,
  FullscreenExit,
  NavigateBefore,
  NavigateNext,
  Search as SearchIcon,
  Tune as TuneIcon,
  Visibility,
  VisibilityOff,
  DragIndicator,
  PlayArrow,
  ShowChart as SignalIcon,
  CheckCircle,
  Notifications,
  NotificationsOutlined,
  Star,
  StarBorder,
  ShoppingCart,
  Info,
  OpenInFull,
  ViewList as ViewListIcon,
} from '@mui/icons-material';
import { Time } from 'lightweight-charts';
import { useSearchParams } from 'react-router-dom';
import { useUpbitData } from '../contexts/UpbitDataContext';
import { useAppTheme } from '../contexts/ThemeContext';
import { useAlertNotification } from '../contexts/AlertNotificationContext';
import CandlestickChart, { ChartHandle } from '../components/CandlestickChart';
import IndicatorChart from '../components/IndicatorChart';
import CryptoNameComboBox from '../components/CryptoNameComboBox';
import CryptoListPanel from '../components/CryptoListPanel';
import MASettingsDialog from '../components/MASettingsDialog';
import IchimokuSettingsDialog from '../components/IchimokuSettingsDialog';
import BollingerSettingsDialog from '../components/BollingerSettingsDialog';
import IndicatorParamsSettingsDialog from '../components/IndicatorParamsSettingsDialog';
import SignalTable, { TradeSimulation } from '../components/SignalTable';
// ChartToolbar 제거 (모바일에서 미사용)
import { useIndicatorVisibility } from '../contexts/IndicatorVisibilityContext';
import { useIndicatorSettings } from '../contexts/IndicatorSettingsContext';
import { useChartColors } from '../contexts/ChartColorContext';
import { runBacktest, BacktestResult, TradeRecord } from '../services/backtestApi';
import { getStrategyRules, StrategyRuleDto } from '../services/strategyRuleApi';
import { analyzeSignals, SignalAnalysisRequest, CandleSignal } from '../services/strategySignalApi';
import { Brightness4, Brightness7 } from '@mui/icons-material';
import FavoritesPanel from '../components/FavoritesPanel';
import { toggleFavorite, checkFavorite } from '../services/cryptoFavoriteApi';

/**
 * Autocomplete 옵션 렌더링 컴포넌트
 */
const CryptoOption: React.FC<{
  option: { symbol: string; koreanName: string; englishName: string };
  liProps: React.HTMLAttributes<HTMLLIElement>;
}> = ({ option, liProps }) => {
  const [isFav, setIsFav] = useState(false);

  useEffect(() => {
    checkFavorite(option.symbol).then(setIsFav).catch(console.error);
  }, [option.symbol]);

  const handleToggleFavorite = async (e: React.MouseEvent) => {
    e.stopPropagation();
    e.preventDefault();
    try {
      const result = await toggleFavorite({
        symbol: option.symbol,
        koreanName: option.koreanName,
        englishName: option.englishName,
      });
      setIsFav(result);
    } catch (error) {
      console.error('즐겨찾기 토글 실패:', error);
    }
  };

  return (
    <Box 
      component="li" 
      {...liProps}
      sx={{ 
        display: 'flex !important', 
        justifyContent: 'space-between !important', 
        alignItems: 'center !important', 
        width: '100% !important',
        padding: '8px 16px !important',
      }}
    >
      {/* 좌측: 한글명 + 영문명 */}
      <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
        <Typography sx={{ fontWeight: 'bold', fontSize: '14px', color: '#ffffff' }}>
          {option.koreanName}
        </Typography>
        <Typography sx={{ fontSize: '12px', color: '#71717a' }}>
          {option.englishName}
        </Typography>
      </Box>

      {/* 우측: 즐겨찾기 아이콘만 */}
      <IconButton
        size="small"
        onClick={handleToggleFavorite}
        sx={{ 
          color: isFav ? '#fbbf24' : '#71717a',
          padding: '4px',
        }}
      >
        {isFav ? <Star /> : <StarBorder />}
      </IconButton>
    </Box>
  );
};

/** 업비트 모바일 스타일: 스크롤 없이 한 화면에 캔들+보조지표 표시 */
const MOBILE_CHART_RATIOS = {
  header: 0.14,
  timeframe: 0.06,
  mainChart: 0.40,
  indicators: 0.40,
};
const MAX_INDICATORS_VISIBLE = 3;

interface MobileChartPageProps {
  /** MobileAppShell 내장 시 true - 고정 높이 컨테이너에 맞춤, 스크롤 없음 */
  embedded?: boolean;
}

const MobileChartPage: React.FC<MobileChartPageProps> = ({ embedded = false }) => {
  const { 
    symbol, 
    setSymbol, 
    timeInterval, 
    setTimeInterval,
    macdData,
    loading,
    error,
    fetchChartData
  } = useUpbitData();

  const [searchParams] = useSearchParams();
  // 앱 WebView / 딥링크: /mobile/chart?symbol=KRW-XXX 또는 ?market=KRW-XXX
  useEffect(() => {
    const q = (searchParams.get('symbol') || searchParams.get('market'))?.trim();
    if (!q) return;
    const upper = q.toUpperCase();
    if (/^(KRW|BTC|USDT)-[A-Z0-9]+$/.test(upper) && upper !== symbol) {
      console.log(`[MobileChartPage] URL symbol apply: ${symbol} -> ${upper}`);
      setSymbol(upper);
    }
  }, [searchParams, setSymbol, symbol]);

  // Android WebView가 종목을 직접 주입하는 이벤트 수신 (URL 쿼리 누락 대비)
  useEffect(() => {
    const handler = (evt: Event) => {
      const custom = evt as CustomEvent<string>;
      const injected = (custom.detail || '').trim().toUpperCase();
      if (!/^(KRW|BTC|USDT)-[A-Z0-9]+$/.test(injected)) return;
      if (injected === symbol) return;
      console.log(`[MobileChartPage] Injected symbol apply: ${symbol} -> ${injected}`);
      setSymbol(injected);
    };
    window.addEventListener('golden-symbol', handler as EventListener);
    return () => window.removeEventListener('golden-symbol', handler as EventListener);
  }, [symbol, setSymbol]);

  // Context 통합
  const { settings: indicatorVisibilitySettings, updateSettings: updateIndicatorSettings } = useIndicatorVisibility();
  const { indicatorSettings: paramSettings } = useIndicatorSettings();
  const { colors: colorSettings } = useChartColors();
  const { themeMode, setThemeMode } = useAppTheme();
  const { latestNotification } = useAlertNotification();
  
  // 테마 토글 함수 (다크 <-> 라이트)
  const toggleTheme = () => {
    setThemeMode(themeMode === 'dark' ? 'light' : 'dark');
  };

  // ✅ 암호화폐 목록 (Autocomplete용)
  const [cryptoList, setCryptoList] = useState<Array<{ symbol: string; koreanName: string; englishName: string }>>([]);
  const selectedCryptoOption = useMemo(
    () =>
      cryptoList.find((c) => c.symbol === symbol) ?? {
        symbol,
        koreanName: symbol,
        englishName: symbol,
      },
    [cryptoList, symbol],
  );
  
  // ✅ 암호화폐 목록 불러오기
  useEffect(() => {
    const fetchCryptoList = async () => {
      try {
        const { upbitApiService } = await import('../services/upbitApi');
        const cryptos = await upbitApiService.getActiveCryptos();
        setCryptoList(cryptos);
      } catch (err) {
        console.error('암호화폐 목록 로드 실패:', err);
      }
    };
    fetchCryptoList();
  }, []);

  // ✅ 즐겨찾기 상태 확인
  useEffect(() => {
    const checkFavoriteStatus = async () => {
      try {
        const favorite = await checkFavorite(symbol);
        setIsFavorite(favorite);
      } catch (err) {
        console.error('즐겨찾기 확인 실패:', err);
      }
    };
    checkFavoriteStatus();
  }, [symbol]);

  // Refs
  const chartRef = useRef<ChartHandle>(null);

  // UI 상태
  const [showSettings, setShowSettings] = useState(false);
  const [showCryptoList, setShowCryptoList] = useState(false);
  const [showIndicatorSettings, setShowIndicatorSettings] = useState(false);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [isFavorite, setIsFavorite] = useState(false);
  const [showFavoritesPanel, setShowFavoritesPanel] = useState(false);

  // 설정 다이얼로그 상태
  const [maSettingsOpen, setMaSettingsOpen] = useState(false);
  const [ichimokuSettingsOpen, setIchimokuSettingsOpen] = useState(false);
  const [bollingerSettingsOpen, setBollingerSettingsOpen] = useState(false);
  const [indicatorParamsSettingsOpen, setIndicatorParamsSettingsOpen] = useState(false);

  // 백테스트 및 시그널 상태
  const [showSignalTable, setShowSignalTable] = useState(false);
  const [backtestResult, setBacktestResult] = useState<BacktestResult | null>(null);
  const [signals, setSignals] = useState<CandleSignal[]>([]);
  const [strategyRules, setStrategyRules] = useState<StrategyRuleDto[]>([]);
  const [selectedStrategyIds, setSelectedStrategyIds] = useState<number[]>([]);
  const [backtestLoading, setBacktestLoading] = useState(false);

  // 차트 툴바 제거 (모바일에서 미사용)
  
  // ✅ 모든 차트 간 시간 범위 동기화
  const [sharedTimeRange, setSharedTimeRange] = useState<{ from: number; to: number } | null>(null);
  
  // ✅ 모든 차트 간 크로스헤어 동기화
  const [sharedHoverTime, setSharedHoverTime] = useState<Time | null>(null);
  
  // ✅ 알림 마커 상태
  const [alertMarkers, setAlertMarkers] = useState<Array<{
    time: Time;
    position: 'aboveBar' | 'belowBar';
    color: string;
    shape: 'arrowUp' | 'arrowDown' | 'circle';
    text: string;
  }>>([]);
  
  const effectiveMainRatio = embedded ? MOBILE_CHART_RATIOS.mainChart : 0.5;
  const [candleChartHeightRatio, setCandleChartHeightRatio] = useState(0.5);
  const mainChartRatio = embedded ? effectiveMainRatio : candleChartHeightRatio;
  const [containerHeight, setContainerHeight] = useState(0);
  const containerRef = useRef<HTMLDivElement>(null);
  const [isResizing, setIsResizing] = useState(false);
  const resizerStartY = useRef<number>(0);
  const initialHeightRatio = useRef<number>(0.5);
  
  const APPBAR_HEIGHT = embedded ? 0 : 80;
  const BOTTOM_NAV_HEIGHT = 0;
  const RESIZER_HEIGHT = embedded ? 0 : 20;
  const INDICATOR_TITLE_HEIGHT = 28;
  const CARD_MARGIN = 8;
  
  useEffect(() => {
    if (!embedded || !containerRef.current) return;
    const ro = new ResizeObserver((entries) => {
      for (const e of entries) {
        const h = e.contentRect.height;
        if (h > 0) setContainerHeight(h);
      }
    });
    ro.observe(containerRef.current);
    return () => ro.disconnect();
  }, [embedded]);
  
  const availableHeight = embedded
    ? (containerHeight > 0 ? containerHeight : typeof window !== 'undefined' ? window.innerHeight - 112 : 500)
    : window.innerHeight - APPBAR_HEIGHT - BOTTOM_NAV_HEIGHT;

  // MacdResult를 CandleData로 변환
  const candleData = useMemo(() => {
    if (!macdData || macdData.length === 0) return [];
    
    return macdData.map((item) => ({
      time: item.timestamp || item.date, // ISO string format
      open: item.open || item.close,
      high: item.high || item.close,
      low: item.low || item.close,
      close: item.close,
      volume: item.volume || 0,
    }));
  }, [macdData]);

  // MacdResult를 IndicatorData로 변환 (보조지표 표시용)
  const indicatorData = useMemo(() => {
    if (!macdData || macdData.length === 0) {
      console.log('⚠️ [MobileChartPage] No macdData for indicators');
      return [];
    }
    
    const data = macdData.map((item) => ({
      time: item.timestamp || item.date,
      timestamp: item.timestamp || item.date,
      open: item.open,
      high: item.high,
      low: item.low,
      close: item.close,
      volume: item.volume,
      macd: item.macdHistogram ?? undefined,
      macdLine: item.macdLine ?? undefined,
      macdSignal: item.signalLine ?? undefined,
      macdHistogram: item.macdHistogram ?? undefined,
      stochasticK: item.stochasticK ?? undefined,
      stochasticD: item.stochasticD ?? undefined,
      adx: item.adx ?? undefined,
      plusDI: item.plusDI ?? undefined,
      minusDI: item.minusDI ?? undefined,
    }));
    
    console.log('📊 [MobileChartPage] Indicator Data:', {
      length: data.length,
      sample: data[0],
      hasVolume: data.some(d => d.volume),
      hasMacd: data.some(d => d.macdLine),
    });
    
    return data;
  }, [macdData]);

  // 모바일 보조지표 초기 설정
  useEffect(() => {
    // 설정이 로드된 후 체크
    const timer = setTimeout(() => {
      // activeIndicators가 0개이면 기본 설정으로 초기화
      const hasAnyActive = indicatorVisibilitySettings.volume || 
                          indicatorVisibilitySettings.macdLine || 
                          indicatorVisibilitySettings.macdHistogram ||
                          indicatorVisibilitySettings.stochasticSlow ||
                          indicatorVisibilitySettings.cci ||
                          indicatorVisibilitySettings.obv;
      
      if (!hasAnyActive) {
        console.log('📱 [MobileChartPage] 보조지표가 모두 꺼져 있어 기본값으로 초기화');
        updateIndicatorSettings({
          volume: true,
          macdLine: true,
          macdHistogram: true,
        });
      } else {
        console.log('📱 [MobileChartPage] 보조지표 설정:', {
          volume: indicatorVisibilitySettings.volume,
          macdLine: indicatorVisibilitySettings.macdLine,
          macdHistogram: indicatorVisibilitySettings.macdHistogram,
        });
      }
    }, 500);
    
    return () => clearTimeout(timer);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [indicatorVisibilitySettings]);

  // standalone 모드에서만 body overflow 제거 (embedded는 부모가 스크롤 제어)
  useEffect(() => {
    if (embedded) return;
    const orig = { overflow: document.body.style.overflow, margin: document.body.style.margin, padding: document.body.style.padding };
    document.body.style.overflow = 'hidden';
    document.body.style.margin = '0';
    document.body.style.padding = '0';
    return () => {
      document.body.style.overflow = orig.overflow;
      document.body.style.margin = orig.margin;
      document.body.style.padding = orig.padding;
    };
  }, [embedded]);

  useEffect(() => {
    // 초기 데이터 로드: URL 쿼리 종목이 있으면 해당 종목 우선
    const q = (searchParams.get('symbol') || searchParams.get('market'))?.trim()?.toUpperCase();
    if (q && /^(KRW|BTC|USDT)-[A-Z0-9]+$/.test(q)) {
      fetchChartData(q, timeInterval);
    } else {
      fetchChartData();
    }
    
    // 전략 규칙 로드
    loadStrategyRules();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // ✅ 알림 발생 시 현재 종목이 알림 대상이면 차트에 마커 표시
  useEffect(() => {
    if (!latestNotification || !latestNotification.message || !candleData || candleData.length === 0) return;

    // 알림 메시지에서 현재 종목 심볼이 포함되어 있는지 확인
    const message = latestNotification.message;
    
    // 종목 심볼 또는 한글 이름으로 매칭 (예: KRW-BTC 또는 "비트코인")
    if (message.includes(symbol)) {
      console.log(`🔔 현재 종목(${symbol})에 대한 알림 발생 - 마커 추가`);
      
      // 현재 시간에 마커 추가 (가장 최근 캔들)
      const latestCandle = candleData[candleData.length - 1];
      const markerTime = typeof latestCandle.time === 'string' 
        ? new Date(latestCandle.time).getTime() / 1000 
        : latestCandle.time;
      
      // 매수/매도 판별 (알림 메시지에서 추출)
      const isBuySignal = message.includes('매수') || message.includes('BUY') || 
                         message.includes('골든크로스') || message.includes('과매도');
      
      const newMarker = {
        time: markerTime as Time,
        position: isBuySignal ? 'belowBar' as const : 'aboveBar' as const,
        color: isBuySignal ? '#26a69a' : '#ef5350',
        shape: isBuySignal ? 'arrowUp' as const : 'arrowDown' as const,
        text: isBuySignal ? '매수' : '매도',
      };
      
      setAlertMarkers(prev => [...prev, newMarker]);
      console.log(`✅ 알림 마커 추가: ${isBuySignal ? '매수' : '매도'} at ${new Date(markerTime * 1000).toLocaleString()}`);
    }
  }, [latestNotification, symbol, candleData]);

  // 전략 규칙 로드
  const loadStrategyRules = async () => {
    try {
      const rules = await getStrategyRules();
      setStrategyRules(rules);
    } catch (error) {
      console.error('Failed to load strategy rules:', error);
    }
  };

  const handleRefresh = () => {
    fetchChartData();
  };

  const handleSymbolChange = (event: any) => {
    setSymbol(event.target.value);
  };

  const handleIntervalChange = (event: any) => {
    setTimeInterval(event.target.value);
  };

  // ✅ 시간 범위 변경 시 모든 차트에 적용 (터치 스크롤 동기화)
  const handleVisibleRangeChange = (from: number, to: number) => {
    setSharedTimeRange({ from, to });
    console.log('📊 [차트 동기화] 시간 범위 변경:', { 
      from: new Date(from * 1000).toLocaleString(), 
      to: new Date(to * 1000).toLocaleString() 
    });
  };

  // ✅ 크로스헤어 이동 시 모든 차트에 적용
  const handleCrosshairMove = (time: Time | null) => {
    setSharedHoverTime(time);
  };

  // 전체화면 토글
  const handleFullscreenToggle = () => {
    setIsFullscreen(!isFullscreen);
  };

  // ✅ 즐겨찾기 토글
  const handleToggleFavorite = async () => {
    try {
      const currentCrypto = cryptoList.find(c => c.symbol === symbol);
      if (!currentCrypto) return;

      const result = await toggleFavorite({
        symbol: symbol,
        koreanName: currentCrypto.koreanName,
        englishName: currentCrypto.englishName,
      });
      
      setIsFavorite(result);
    } catch (err) {
      console.error('즐겨찾기 토글 실패:', err);
    }
  };
  
  // ✅ 리사이저 드래그 시작 (터치 이벤트 개선)
  const handleResizerMouseDown = (e: React.MouseEvent | React.TouchEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsResizing(true);
    
    const clientY = 'touches' in e ? e.touches[0].clientY : e.clientY;
    resizerStartY.current = clientY;
    initialHeightRatio.current = candleChartHeightRatio;
    
    const availableHeight = window.innerHeight - APPBAR_HEIGHT - BOTTOM_NAV_HEIGHT;
    const currentResizerPosition = APPBAR_HEIGHT + (availableHeight * candleChartHeightRatio);
    
    console.log('📏 [리사이저] 드래그 시작:', { 
      clientY, 
      initialRatio: candleChartHeightRatio.toFixed(2),
      availableHeight,
      appBarHeight: APPBAR_HEIGHT,
      currentResizerPosition: currentResizerPosition.toFixed(0),
      windowHeight: window.innerHeight
    });
  };
  
  // ✅ 리사이저 드래그 중 (터치 이벤트 개선)
  useEffect(() => {
    if (!isResizing) return;
    
    const handleMove = (e: MouseEvent | TouchEvent) => {
      e.preventDefault(); // 스크롤 방지
      
      const clientY = 'touches' in e ? (e as TouchEvent).touches[0].clientY : (e as MouseEvent).clientY;
      const deltaY = clientY - resizerStartY.current;
      
      // ✅ availableHeight를 직접 사용 (window.innerHeight 기반)
      const availableHeight = window.innerHeight - APPBAR_HEIGHT - BOTTOM_NAV_HEIGHT;
      const deltaRatio = deltaY / availableHeight;
      
      let newRatio = initialHeightRatio.current + deltaRatio;
      const beforeClamp = newRatio;
      // 최소 30%, 최대 80%로 제한
      newRatio = Math.max(0.3, Math.min(0.8, newRatio));
      
      const expectedResizerPosition = APPBAR_HEIGHT + (availableHeight * newRatio);
      
      // ✅ 실시간 업데이트로 리사이저 바가 드래그 위치로 이동
      setCandleChartHeightRatio(newRatio);
      console.log('📏 [리사이저] 드래그 중:', { 
        clientY, 
        startY: resizerStartY.current,
        deltaY, 
        deltaRatio: deltaRatio.toFixed(3),
        initialRatio: initialHeightRatio.current.toFixed(2),
        beforeClamp: beforeClamp.toFixed(3),
        newRatio: newRatio.toFixed(2),
        expectedPosition: expectedResizerPosition.toFixed(0),
        clamped: beforeClamp !== newRatio
      });
    };
    
    const handleEnd = () => {
      setIsResizing(false);
      console.log('📏 [리사이저] 드래그 종료');
    };
    
    // passive: false로 설정하여 preventDefault 가능하게
    document.addEventListener('mousemove', handleMove);
    document.addEventListener('mouseup', handleEnd);
    document.addEventListener('touchmove', handleMove, { passive: false });
    document.addEventListener('touchend', handleEnd);
    document.addEventListener('touchcancel', handleEnd);
    
    return () => {
      document.removeEventListener('mousemove', handleMove);
      document.removeEventListener('mouseup', handleEnd);
      document.removeEventListener('touchmove', handleMove);
      document.removeEventListener('touchend', handleEnd);
      document.removeEventListener('touchcancel', handleEnd);
    };
  }, [isResizing]); // ✅ candleChartHeightRatio 제거하여 드래그 중 재등록 방지

  // 기간 이동 (이전/다음)
  const handleNavigate = (direction: 'past' | 'future') => {
    if (chartRef.current) {
      // CandlestickChart의 네비게이션 기능 사용
      console.log(`Navigate to ${direction}`);
      // TODO: 실제 데이터 로딩 구현 필요
    }
  };

  // 종목 변경 핸들러
  const handleCryptoSelect = (market: string) => {
    setSymbol(market);
    setShowCryptoList(false);
  };

  // 백테스트 실행
  const handleRunBacktest = async () => {
    if (!candleData || candleData.length === 0 || selectedStrategyIds.length === 0) {
      return;
    }

    setBacktestLoading(true);
    try {
      // 날짜 범위 계산 (최근 30일)
      const endDate = new Date();
      const startDate = new Date();
      startDate.setDate(startDate.getDate() - 30);

      // 첫 번째 전략으로 백테스트 실행
      const result = await runBacktest({
        symbol,
        timeframe: timeInterval,
        strategyId: 0, // 기본 전략 ID
        uptrendStrategyId: selectedStrategyIds[0], // 첫 번째 선택된 전략
        downtrendStrategyId: selectedStrategyIds[0], // 동일한 전략 사용
        startDate: startDate.toISOString(),
        endDate: endDate.toISOString(),
        initialCapital: 100000000, // 1억
        positionSizeRatio: 1.0,
        commissionRate: 0.0005,
      });

      setBacktestResult(result);
      
      // 시그널 분석
      const signalAnalysisRequest: SignalAnalysisRequest = {
        symbol,
        interval: timeInterval,
        candleData: candleData.map((candle) => ({
          time: candle.time,
          open: candle.open,
          high: candle.high,
          low: candle.low,
          close: candle.close,
          volume: candle.volume,
        })),
        indicatorData: indicatorData,
        uptrendStrategyId: selectedStrategyIds[0],
        downtrendStrategyId: selectedStrategyIds[0],
      };
      const signalsResult = await analyzeSignals(signalAnalysisRequest);
      setSignals(signalsResult.signals); // ✅ SignalAnalysisResponse.signals 사용

      setShowSignalTable(true);
    } catch (error) {
      console.error('Backtest failed:', error);
    } finally {
      setBacktestLoading(false);
    }
  };

  // 시그널 테이블 데이터 변환
  const tradeSimulations: TradeSimulation[] = useMemo(() => {
    if (!backtestResult || !backtestResult.tradeRecords) return [];

    return backtestResult.tradeRecords.map((trade: TradeRecord) => ({
      date: trade.timestamp,
      timestamp: trade.timestamp,
      signal: trade.tradeType, // 'BUY' | 'SELL'
      price: trade.price,
      quantity: trade.quantity,
      tradeAmount: trade.totalAmount,
      commission: trade.commission,
      netAmount: trade.totalAmount - trade.commission,
      holdingQty: trade.holdings,
      avgBuyPrice: trade.holdings > 0 ? (trade.balance / trade.holdings) : 0,
      profitLoss: trade.profitLoss || 0,
      profitLossRate: trade.returnRate || 0,
      totalAsset: trade.balance,
      macdData: indicatorData.find(d => d.timestamp === trade.timestamp) || {} as any,
    }));
  }, [backtestResult, indicatorData]);

  // 보조지표 토글 핸들러
  const handleIndicatorToggle = (indicatorKey: keyof typeof indicatorVisibilitySettings) => {
    updateIndicatorSettings({
      [indicatorKey]: !indicatorVisibilitySettings[indicatorKey]
    });
  };

  // 활성화된 보조지표 목록
  const activeIndicators = useMemo(() => {
    const indicators: Array<{
      key: string;
      type: string;
      label: string;
      isActive: boolean;
    }> = [
      { key: 'volume', type: 'volume', label: 'Volume', isActive: indicatorVisibilitySettings.volume },
      { key: 'macd', type: 'macd', label: 'MACD', isActive: indicatorVisibilitySettings.macdLine || indicatorVisibilitySettings.macdHistogram },
      { key: 'rsi', type: 'rsi', label: 'RSI', isActive: indicatorVisibilitySettings.rsi },
      { key: 'stochastic', type: 'stochastic', label: 'Stochastic Slow', isActive: indicatorVisibilitySettings.stochasticSlow },
      { key: 'cci', type: 'cci', label: 'CCI', isActive: indicatorVisibilitySettings.cci },
      { key: 'adx', type: 'adx', label: 'ADX', isActive: indicatorVisibilitySettings.adx },
      { key: 'obv', type: 'obv', label: 'OBV', isActive: indicatorVisibilitySettings.obv },
      { key: 'newPsychological', type: 'newPsychological', label: '신심리도', isActive: indicatorVisibilitySettings.newPsychological },
      { key: 'investPsychological', type: 'investPsychological', label: '투자심리도', isActive: indicatorVisibilitySettings.investPsychological },
    ];
    
    const activeList = indicators.filter(ind => ind.isActive);
    if (embedded && activeList.length > MAX_INDICATORS_VISIBLE) {
      return activeList.slice(0, MAX_INDICATORS_VISIBLE);
    }
    return activeList;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [indicatorVisibilitySettings, embedded]);

  // 주요 암호화폐 목록
  const cryptoSymbols = [
    'KRW-BTC',
    'KRW-ETH',
    'KRW-XRP',
    'KRW-ADA',
    'KRW-DOGE',
    'KRW-SOL',
    'KRW-MATIC',
    'KRW-AVAX',
    'KRW-DOT',
    'KRW-LINK',
  ];

  // 시간 간격 옵션 (UpbitDataContext와 일치하는 형식)
  const intervals = [
    { value: '1m', label: '1분' },
    { value: '3m', label: '3분' },
    { value: '5m', label: '5분' },
    { value: '15m', label: '15분' },
    { value: '30m', label: '30분' },
    { value: '1h', label: '1시간' },
    { value: '4h', label: '4시간' },
    { value: '1d', label: '일봉' },
    { value: '1w', label: '주봉' },
    { value: '1M', label: '월봉' },
  ];

  // ✅ 시간봉 선택 탭 (업비트 스타일)
  const timeIntervalTabs = [
    { label: '1M', value: '1' },
    { label: '3M', value: '3' },
    { label: '5M', value: '5' },
    { label: '10M', value: '10' },
    { label: '1H', value: '60' },
    { label: '1D', value: 'D' },
  ];

  // 현재 가격 및 변동률 계산
  const currentPrice = useMemo(() => {
    if (!candleData || candleData.length === 0) return 0;
    return candleData[candleData.length - 1]?.close || 0;
  }, [candleData]);

  const priceChange = useMemo(() => {
    if (!candleData || candleData.length < 2) return 0;
    const current = candleData[candleData.length - 1]?.close || 0;
    const previous = candleData[candleData.length - 2]?.close || 0;
    if (previous === 0) return 0;
    return ((current - previous) / previous) * 100;
  }, [candleData]);

  // 코인 이름 추출
  const coinName = useMemo(() => {
    const parts = symbol.split('-');
    if (parts.length === 2) {
      return `${parts[1]} (${parts[1]}/${parts[0]})`;
    }
    return symbol;
  }, [symbol]);

  return (
    <Box
      ref={containerRef}
      sx={{
        width: '100%',
        height: embedded ? '100%' : '100vh',
        display: 'flex',
        flexDirection: 'column',
        bgcolor: '#0C111D',
        overflow: 'hidden',
        touchAction: 'pan-y',
        WebkitOverflowScrolling: 'touch',
        margin: 0,
        padding: 0,
        ...(embedded ? {} : { position: 'fixed', top: 0, left: 0, right: 0, bottom: 0 }),
      }}
    >
      {/* 즐겨찾기 패널 */}
      <FavoritesPanel
        open={showFavoritesPanel}
        onClose={() => setShowFavoritesPanel(false)}
        onSelectSymbol={setSymbol}
        currentSymbol={symbol}
      />

      {/* 즐겨찾기 패널 토글 버튼 */}
      {!isFullscreen && !showFavoritesPanel && (
        <Fab
          size="small"
          onClick={() => setShowFavoritesPanel(true)}
          sx={{
            position: 'fixed',
            left: 8,
            top: '50%',
            transform: 'translateY(-50%)',
            bgcolor: '#1a1f2e',
            color: '#fbbf24',
            zIndex: 1100,
            '&:hover': {
              bgcolor: '#252a3a',
            },
            boxShadow: '0 4px 12px rgba(0,0,0,0.4)',
          }}
        >
          <ViewListIcon />
        </Fab>
      )}

      {/* 상단 헤더: embedded=업비트 스타일 컴팩트(한줄), 아니면 2라인 */}
      {!isFullscreen && (
        <Box
          sx={{
            bgcolor: '#0C111D',
            px: embedded ? 1 : 1,
            pt: embedded ? 0.5 : 1,
            pb: embedded ? 0.5 : 0.5,
            flexShrink: 0,
          }}
        >
          <Box
            sx={{
              bgcolor: '#1a1f2e',
              borderRadius: embedded ? 1 : 2,
              px: embedded ? 1 : 1.5,
              py: embedded ? 0.75 : 1,
              boxShadow: '0 2px 8px rgba(0,0,0,0.3)',
            }}
          >
            {embedded ? (
              /* 업비트 스타일: 한 줄에 종목+가격+변동률 */
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 1, flexWrap: 'nowrap' }}>
                <Autocomplete
                  size="small"
                  options={cryptoList}
                  getOptionLabel={(o) => `${o.koreanName} (${o.symbol.replace('KRW-', '')})`}
                  value={selectedCryptoOption}
                  onChange={(_, v) => v && setSymbol(v.symbol)}
                  disableClearable
                  sx={{
                    flex: 1,
                    minWidth: 0,
                    '& .MuiAutocomplete-inputRoot': { bgcolor: 'transparent', color: '#fff', fontSize: '13px' },
                    '& .MuiOutlinedInput-notchedOutline': { border: 'none' },
                  }}
                  renderInput={(p) => <TextField {...p} variant="outlined" size="small" placeholder="종목 선택" />}
                  renderOption={(props, o) => <CryptoOption option={o} liProps={props} />}
                  ListboxProps={{ sx: { bgcolor: '#1a1f2e' } }}
                />
                <Typography sx={{ fontSize: '15px', fontWeight: 700, color: priceChange >= 0 ? '#ef4444' : '#3b82f6', whiteSpace: 'nowrap' }}>
                  {currentPrice.toLocaleString()}
                </Typography>
                <Chip
                  label={`${priceChange >= 0 ? '▲' : '▼'}${Math.abs(priceChange).toFixed(2)}%`}
                  size="small"
                  sx={{ height: 18, fontSize: '10px', bgcolor: priceChange >= 0 ? '#ef4444' : '#3b82f6', color: '#fff' }}
                />
                <IconButton size="small" onClick={() => setIsFavorite(!isFavorite)} sx={{ p: 0.25 }}>
                  {isFavorite ? <Star sx={{ fontSize: 18, color: '#f59e0b' }} /> : <StarBorder sx={{ fontSize: 18, color: '#71717a' }} />}
                </IconButton>
              </Box>
            ) : (
            <>
            {/* 첫 줄: 종목 선택 + 아이콘 버튼들 */}
            <Box
              sx={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                mb: 0.5,
              }}
            >
              {/* 좌측: 종목 선택 */}
              <Autocomplete
                options={cryptoList}
                getOptionLabel={(option) => `${option.koreanName} (${option.symbol.replace('KRW-', '')})`}
                value={selectedCryptoOption}
                onChange={(event, newValue) => {
                  if (newValue) {
                    setSymbol(newValue.symbol);
                  }
                }}
                disableClearable
                sx={{
                  flex: 1,
                  maxWidth: '320px',
                  '& .MuiAutocomplete-inputRoot': {
                    bgcolor: 'transparent',
                    color: '#ffffff',
                    fontSize: '14px',
                    fontWeight: 600,
                    padding: '0px',
                    minHeight: 'auto',
                  },
                  '& .MuiOutlinedInput-notchedOutline': {
                    border: 'none',
                  },
                  '& .MuiAutocomplete-popupIndicator': {
                    color: '#71717a',
                  },
                }}
                renderInput={(params) => (
                  <TextField
                    {...params}
                    placeholder="종목 선택"
                    variant="outlined"
                  />
                )}
                renderOption={(props, option) => (
                  <CryptoOption option={option} liProps={props} />
                )}
                ListboxProps={{
                  sx: {
                    bgcolor: '#1a1f2e',
                    color: '#ffffff',
                    maxHeight: '400px',
                    width: '380px',
                    '& .MuiAutocomplete-option': {
                      '&:hover': {
                        bgcolor: 'rgba(255, 255, 255, 0.1)',
                      },
                      '&[aria-selected="true"]': {
                        bgcolor: 'rgba(33, 150, 243, 0.2)',
                      },
                    },
                  },
                }}
              />

              {/* 우측: 아이콘 버튼들 */}
              <Box sx={{ display: 'flex', gap: 0.5 }}>
                <IconButton
                  size="small"
                  sx={{ color: '#71717a', p: 0.5 }}
                >
                  <NotificationsOutlined sx={{ fontSize: 18 }} />
                </IconButton>
                <IconButton
                  size="small"
                  onClick={() => setIsFavorite(!isFavorite)}
                  sx={{ color: isFavorite ? '#f59e0b' : '#71717a', p: 0.5 }}
                >
                  {isFavorite ? <Star sx={{ fontSize: 18 }} /> : <StarBorder sx={{ fontSize: 18 }} />}
                </IconButton>
                <IconButton
                  size="small"
                  onClick={handleFullscreenToggle}
                  sx={{ color: '#71717a', p: 0.5 }}
                >
                  <OpenInFull sx={{ fontSize: 18 }} />
                </IconButton>
              </Box>
            </Box>

            {/* 둘째 줄: 가격 + 변동률 (한 줄에) */}
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
              <Typography
                sx={{
                  fontSize: '20px',
                  fontWeight: 700,
                  color: priceChange >= 0 ? '#ef4444' : '#3b82f6',
                }}
              >
                {currentPrice.toLocaleString()}
              </Typography>
              <Typography
                sx={{
                  fontSize: '11px',
                  fontWeight: 600,
                  color: '#71717a',
                }}
              >
                KRW
              </Typography>
              <Chip
                label={`${priceChange >= 0 ? '▲' : '▼'}${Math.abs(priceChange).toFixed(2)}%`}
                size="small"
                sx={{
                  bgcolor: priceChange >= 0 ? '#ef4444' : '#3b82f6',
                  color: '#ffffff',
                  fontWeight: 700,
                  fontSize: '11px',
                  height: 20,
                  borderRadius: 1,
                  '& .MuiChip-label': {
                    px: 1,
                  },
                }}
              />
            </Box>
            </>
            )}
          </Box>
        </Box>
      )}

      {/* 차트 카드 박스 (flex:1로 남은 공간 채움, 스크롤 없음) */}
      <Box
        sx={{
          bgcolor: '#0C111D',
          px: embedded ? 0.5 : 1,
          pt: 0,
          pb: embedded ? 0.5 : 1,
          flex: 1,
          minHeight: 0,
          overflow: 'hidden',
        }}
      >
        <Box
          sx={{
            bgcolor: '#1a1f2e',
            borderRadius: 2,
            height: '100%',
            boxShadow: '0 2px 8px rgba(0,0,0,0.3)',
            overflow: 'hidden',
            display: 'flex',
            flexDirection: 'column',
          }}
        >
          {/* 시간봉 탭 (업비트 스타일 얇은 스트립) */}
          <Box
            sx={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              borderBottom: '1px solid rgba(255, 255, 255, 0.05)',
              px: embedded ? 0.5 : 1,
              py: embedded ? 0.25 : 0,
              flexShrink: 0,
            }}
          >
            <Box sx={{ display: 'flex', gap: 0 }}>
              {timeIntervalTabs.map((tab) => (
                <Box
                  key={tab.value}
                  onClick={() => setTimeInterval(tab.value)}
                  sx={{
                    px: embedded ? 1.5 : 2,
                    py: embedded ? 0.75 : 1.5,
                    cursor: 'pointer',
                    borderBottom: timeInterval === tab.value ? '2px solid #ffffff' : '2px solid transparent',
                    transition: 'all 0.2s',
                  }}
                >
                  <Typography
                    sx={{
                      fontSize: embedded ? '12px' : '13px',
                      fontWeight: timeInterval === tab.value ? 700 : 400,
                      color: timeInterval === tab.value ? '#ffffff' : '#71717a',
                    }}
                  >
                    {tab.label}
                  </Typography>
                </Box>
              ))}
            </Box>
            <IconButton
              size="small"
              sx={{ color: '#71717a' }}
            >
              <OpenInFull fontSize="small" />
            </IconButton>
          </Box>

          {/* MA 정보 오버레이 */}
          <Box
            sx={{
              position: 'absolute',
              top: 50,
              left: 8,
              zIndex: 10,
              display: 'flex',
              gap: 2,
            }}
          >
            <Typography sx={{ fontSize: '11px', color: '#ef4444', fontWeight: 600 }}>
              MA 13,000
            </Typography>
            <Typography sx={{ fontSize: '11px', color: '#3b82f6', fontWeight: 600 }}>
              MA 4,000
            </Typography>
            <Typography sx={{ fontSize: '11px', color: '#22c55e', fontWeight: 600 }}>
              MA 1950
            </Typography>
            <Typography
              sx={{
                fontSize: '11px',
                fontWeight: 600,
                color: priceChange >= 0 ? '#ef4444' : '#3b82f6',
              }}
            >
              {priceChange >= 0 ? '+' : ''}{priceChange.toFixed(2)}%
            </Typography>
          </Box>

          {/* 차트 컨테이너 */}
          <Box
            sx={{
              position: 'relative',
              flex: 1,
              width: '100%',
              overflow: 'hidden',
            }}
          >
        {/* 전체화면 모드 종료 버튼 */}
        {isFullscreen && (
          <IconButton
            onClick={handleFullscreenToggle}
            sx={{
              position: 'absolute',
              top: 8,
              right: 8,
              zIndex: 1200,
              bgcolor: 'rgba(0, 0, 0, 0.5)',
              color: 'white',
              '&:hover': {
                bgcolor: 'rgba(0, 0, 0, 0.7)',
              },
            }}
          >
            <FullscreenExit />
          </IconButton>
        )}
        {loading && (
          <Box
            sx={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              bgcolor: 'rgba(0, 0, 0, 0.5)',
              zIndex: 1000,
            }}
          >
            <CircularProgress />
          </Box>
        )}

        {error && (
          <Box sx={{ p: 2 }}>
            <Alert severity="error" onClose={() => {}}>
              {error}
            </Alert>
          </Box>
        )}

        {!loading && !error && candleData && candleData.length > 0 && (
          <Box sx={{ position: 'relative', height: '100%', overflow: 'hidden', bgcolor: '#0C111D', margin: 0, padding: 0 }}>
            {/* 캔들스틱 차트 */}
            <Box 
              sx={{ 
                height: `${availableHeight * mainChartRatio}px`,
                position: 'absolute',
                top: 0,
                left: 0,
                right: 0,
                minHeight: '200px',
                bgcolor: '#0C111D',
                margin: 0,
                padding: 0,
              }}
            >
              <CandlestickChart
                ref={chartRef}
                data={candleData}
                indicatorData={indicatorData}
                height={Math.floor(availableHeight * mainChartRatio)}
                showLeftButton={false}
                showRightButton={false}
                onTimeRangeChange={() => {}}
                onCrosshairMove={handleCrosshairMove}
                onVisibleRangeChange={handleVisibleRangeChange}
                onNavigate={handleNavigate}
                externalHoverTime={sharedHoverTime}
                isMobileMode={true}
                sharedTimeRange={sharedTimeRange}
                indicatorSettings={paramSettings}
                colorSettings={colorSettings}
                alertMarkers={alertMarkers}
              />

            </Box>

            {/* 리사이저 (드래그 핸들) - 터치 영역 확대 */}
            {!isFullscreen && activeIndicators.length > 0 && (
              <Box
                onMouseDown={handleResizerMouseDown}
                onTouchStart={handleResizerMouseDown}
                sx={{
                  height: '20px', // ✅ 터치 영역 확대 (8px -> 20px)
                  position: 'absolute', // ✅ 절대 위치로 변경
                  top: `${availableHeight * mainChartRatio}px`, // ✅ 캔들차트 바로 아래
                  left: 0,
                  right: 0,
                  bgcolor: 'transparent',
                  cursor: 'ns-resize',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  transition: 'background-color 0.2s',
                  touchAction: 'none', // ✅ 터치 스크롤 방지
                  userSelect: 'none',
                  WebkitUserSelect: 'none',
                  zIndex: 1100,
                  '&:active': {
                    bgcolor: 'rgba(33, 150, 243, 0.1)',
                  },
                }}
              >
                {/* 시각적 핸들 */}
                <Box
                  sx={{
                    width: '60px',
                    height: '4px',
                    bgcolor: isResizing ? 'primary.main' : '#71717a',
                    borderRadius: '2px',
                    transition: 'all 0.2s',
                    boxShadow: isResizing ? '0 0 8px rgba(33, 150, 243, 0.5)' : 'none',
                  }}
                />
              </Box>
            )}

            {/* 보조지표 차트들 - 정확한 높이 계산으로 한 화면에 모두 표시 */}
            {!isFullscreen && activeIndicators.length > 0 && (() => {
              // 보조지표 영역 전체 높이
              const indicatorAreaHeight = availableHeight * (1 - mainChartRatio) - RESIZER_HEIGHT;
              // 각 보조지표 높이 (타이틀이 오버레이되므로 전체 높이 사용)
              const singleIndicatorHeight = Math.floor(indicatorAreaHeight / activeIndicators.length);
              
              console.log(`[MobileChartPage] Height Calculation:`, {
                windowHeight: window.innerHeight,
                appBarHeight: APPBAR_HEIGHT,
                bottomNavHeight: BOTTOM_NAV_HEIGHT,
                availableHeight,
                candleChartHeight: availableHeight * mainChartRatio,
                resizerHeight: RESIZER_HEIGHT,
                indicatorAreaTop: availableHeight * mainChartRatio + RESIZER_HEIGHT,
                indicatorAreaHeight,
                activeIndicatorsCount: activeIndicators.length,
                singleIndicatorHeight,
                indicatorDataLength: indicatorData?.length || 0,
              });
              
              return (
                <Box 
                  sx={{ 
                    position: 'absolute', // ✅ 절대 위치로 변경
                    top: `${availableHeight * mainChartRatio + RESIZER_HEIGHT}px`, // ✅ 리사이저 바로 아래
                    left: 0,
                    right: 0,
                    height: `${indicatorAreaHeight}px`,
                    display: 'flex',
                    flexDirection: 'column',
                    overflow: 'hidden',
                    bgcolor: '#0C111D',
                  }}
                >
                  {activeIndicators.map((indicator, index) => (
                    <Box
                      key={indicator.key}
                      sx={{
                        height: `${singleIndicatorHeight}px`,
                        bgcolor: '#0C111D',
                        borderTop: index === 0 ? 'none' : '1px solid rgba(255, 255, 255, 0.05)',
                        display: 'flex',
                        flexDirection: 'column',
                        flex: 'none',
                        overflow: 'hidden',
                        position: 'relative',
                      }}
                    >
                      {/* ✅ 보조지표 타이틀을 차트 내부 상단 좌측에 오버레이 */}
                      <Box
                        onClick={() => setShowSettings(true)}
                        sx={{
                          position: 'absolute',
                          top: 8,
                          left: 8,
                          zIndex: 10,
                          bgcolor: 'rgba(12, 17, 29, 0.8)',
                          backdropFilter: 'blur(4px)',
                          px: 1.5,
                          py: 0.5,
                          borderRadius: 1,
                          border: '1px solid rgba(255, 255, 255, 0.1)',
                          cursor: 'pointer',
                          '&:hover': {
                            bgcolor: 'rgba(12, 17, 29, 0.95)',
                            borderColor: 'rgba(255, 255, 255, 0.2)',
                          },
                          '&:active': {
                            transform: 'scale(0.98)',
                          },
                          transition: 'all 0.2s',
                        }}
                      >
                        <Typography variant="caption" sx={{ fontWeight: 600, fontSize: '11px', color: '#a1a1aa' }}>
                          {indicator.label}
                        </Typography>
                      </Box>
                      
                      {/* ✅ 차트 영역 (타이틀 높이 포함하여 전체 높이 사용) */}
                      <Box sx={{ height: `${singleIndicatorHeight}px`, position: 'relative', flex: 'none', overflow: 'hidden', bgcolor: '#0C111D' }}>
                        <IndicatorChart
                          type={indicator.type as any}
                          data={indicatorData}
                          height={singleIndicatorHeight}
                          onCrosshairMove={handleCrosshairMove}
                          onVisibleRangeChange={handleVisibleRangeChange}
                          externalHoverTime={sharedHoverTime}
                          hideNativeCrosshair={true}
                          sharedTimeRange={sharedTimeRange}
                          isMobileMode={true}
                          hideTimeScale={index !== activeIndicators.length - 1}
                        />
                      </Box>
                    </Box>
                  ))}
                </Box>
              );
            })()}
          </Box>
        )}

        {!loading && !error && (!candleData || candleData.length === 0) && (
          <Box
            sx={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              height: '100%',
            }}
          >
            <Typography variant="body1" color="text.secondary">
              데이터를 불러오는 중...
            </Typography>
          </Box>
        )}
          </Box>
        </Box>
      </Box>

      {/* 종목 리스트 패널 (Drawer) */}
      <Drawer
        anchor="left"
        open={showCryptoList}
        onClose={() => setShowCryptoList(false)}
        PaperProps={{
          sx: {
            bgcolor: '#151B28',
            color: '#ffffff',
          }
        }}
      >
        <Box sx={{ width: 300, p: 2 }}>
          <Typography variant="h6" sx={{ mb: 2, color: '#ffffff' }}>
            종목 선택
          </Typography>
          <Divider sx={{ mb: 2, borderColor: 'rgba(255, 255, 255, 0.1)' }} />
          <CryptoListPanel
            currentSymbol={symbol}
            onSelectSymbol={handleCryptoSelect}
          />
        </Box>
      </Drawer>

      {/* 보조지표 설정 패널 (Drawer) */}
      <Drawer
        anchor="right"
        open={showIndicatorSettings}
        onClose={() => setShowIndicatorSettings(false)}
        PaperProps={{
          sx: {
            bgcolor: '#151B28',
            color: '#ffffff',
          }
        }}
      >
        <Box sx={{ width: 300, p: 2 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
            <Typography variant="h6" sx={{ flexGrow: 1, color: '#ffffff' }}>
              보조지표 설정
            </Typography>
            <IconButton size="small" onClick={() => setShowIndicatorSettings(false)} sx={{ color: '#ffffff' }}>
              <SettingsIcon />
            </IconButton>
          </Box>
          <Divider sx={{ mb: 2, borderColor: 'rgba(255, 255, 255, 0.1)' }} />
          
          {/* 차트 설정 바로가기 */}
          <Box sx={{ mb: 2 }}>
            <Typography variant="subtitle2" sx={{ mb: 1, color: '#71717a' }}>
              차트 설정
            </Typography>
            <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
              <Button
                variant="outlined"
                size="small"
                onClick={() => setMaSettingsOpen(true)}
              >
                이동평균선
              </Button>
              <Button
                variant="outlined"
                size="small"
                onClick={() => setIchimokuSettingsOpen(true)}
              >
                일목균형표
              </Button>
              <Button
                variant="outlined"
                size="small"
                onClick={() => setBollingerSettingsOpen(true)}
              >
                볼린저밴드
              </Button>
              <Button
                variant="outlined"
                size="small"
                onClick={() => setIndicatorParamsSettingsOpen(true)}
              >
                지표 파라미터
              </Button>
            </Box>
          </Box>

          <Divider sx={{ my: 2, borderColor: 'rgba(255, 255, 255, 0.1)' }} />

          <Typography variant="subtitle2" sx={{ mb: 1, color: '#71717a' }}>
            보조지표 표시/숨김 ({activeIndicators.length})
          </Typography>
          
          <List dense>
            {[
              { key: 'volume', label: '거래량' },
              { key: 'macdLine', label: 'MACD' },
              { key: 'rsi', label: 'RSI' },
              { key: 'stochasticSlow', label: 'Stochastic' },
              { key: 'cci', label: 'CCI' },
              { key: 'adx', label: 'ADX' },
              { key: 'obv', label: 'OBV' },
              { key: 'newPsychological', label: '심리선' },
              { key: 'bwi', label: 'BWI' },
              { key: 'plusDi', label: 'DMI' },
              { key: 'williamsR', label: 'Williams %R' },
              { key: 'trix', label: 'TRIX' },
              { key: 'volumeOsc', label: 'Volume Osc' },
              { key: 'vr', label: 'VR' },
              { key: 'disparity', label: 'Disparity' },
            ].map((indicator) => (
              <ListItem key={indicator.key} sx={{ px: 0 }}>
                <ListItemText primary={indicator.label} sx={{ color: '#ffffff' }} />
                <ListItemSecondaryAction>
                  <Switch
                    edge="end"
                    checked={indicatorVisibilitySettings[indicator.key as keyof typeof indicatorVisibilitySettings] as boolean}
                    onChange={() => handleIndicatorToggle(indicator.key as keyof typeof indicatorVisibilitySettings)}
                    size="small"
                  />
                </ListItemSecondaryAction>
              </ListItem>
            ))}
          </List>
        </Box>
      </Drawer>

      {/* 이동평균선 설정 다이얼로그 */}
      <MASettingsDialog
        open={maSettingsOpen}
        onClose={() => setMaSettingsOpen(false)}
      />

      {/* 일목균형표 설정 다이얼로그 */}
      <IchimokuSettingsDialog
        open={ichimokuSettingsOpen}
        onClose={() => setIchimokuSettingsOpen(false)}
      />

      {/* 볼린저밴드 설정 다이얼로그 */}
      <BollingerSettingsDialog
        open={bollingerSettingsOpen}
        onClose={() => setBollingerSettingsOpen(false)}
      />

      {/* 지표 파라미터 설정 다이얼로그 */}
      <IndicatorParamsSettingsDialog
        open={indicatorParamsSettingsOpen}
        onClose={() => setIndicatorParamsSettingsOpen(false)}
      />

      {/* 시그널 테이블 & 백테스트 (Drawer) */}
      <Drawer
        anchor="bottom"
        open={showSignalTable}
        onClose={() => setShowSignalTable(false)}
        PaperProps={{
          sx: {
            bgcolor: '#151B28',
            color: '#ffffff',
          }
        }}
      >
        <Box sx={{ height: '70vh', p: 2, overflowY: 'auto' }}>
          <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
            <Typography variant="h6" sx={{ flexGrow: 1, color: '#ffffff' }}>
              매매 시그널
            </Typography>
            <IconButton size="small" onClick={() => setShowSignalTable(false)} sx={{ color: '#ffffff' }}>
              <FullscreenExit />
            </IconButton>
          </Box>

          {/* 전략 선택 */}
          <Box sx={{ mb: 2 }}>
            <Typography variant="subtitle2" sx={{ mb: 1, color: '#ffffff' }}>
              전략 선택
            </Typography>
            <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
              {strategyRules.map((rule) => (
                <Chip
                  key={rule.id}
                  label={rule.name}
                  onClick={() => {
                    setSelectedStrategyIds((prev) =>
                      prev.includes(rule.id!)
                        ? prev.filter((id) => id !== rule.id)
                        : [...prev, rule.id!]
                    );
                  }}
                  color={selectedStrategyIds.includes(rule.id!) ? 'primary' : 'default'}
                  icon={selectedStrategyIds.includes(rule.id!) ? <CheckCircle /> : undefined}
                  size="small"
                />
              ))}
            </Box>
          </Box>

          {/* 백테스트 실행 버튼 */}
          <Button
            variant="contained"
            fullWidth
            startIcon={<PlayArrow />}
            onClick={handleRunBacktest}
            disabled={backtestLoading || selectedStrategyIds.length === 0}
            sx={{ mb: 2 }}
          >
            {backtestLoading ? '실행 중...' : '백테스트 실행'}
          </Button>

          {/* 백테스트 결과 요약 */}
          {backtestResult && (
            <Box sx={{ mb: 2, p: 2, bgcolor: '#0C111D', borderRadius: 1 }}>
              <Typography variant="subtitle2" gutterBottom sx={{ color: '#ffffff' }}>
                백테스트 결과
              </Typography>
              <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 1 }}>
                <Box>
                  <Typography variant="caption" sx={{ color: '#71717a' }}>
                    최종 잔액
                  </Typography>
                  <Typography variant="body2" fontWeight="bold" sx={{ color: '#ffffff' }}>
                    {backtestResult.finalCapital?.toLocaleString()} 원
                  </Typography>
                </Box>
                <Box>
                  <Typography variant="caption" sx={{ color: '#71717a' }}>
                    수익률
                  </Typography>
                  <Typography
                    variant="body2"
                    fontWeight="bold"
                    color={backtestResult.returnRate >= 0 ? '#22c55e' : '#ef4444'}
                  >
                    {backtestResult.returnRate?.toFixed(2)}%
                  </Typography>
                </Box>
                <Box>
                  <Typography variant="caption" sx={{ color: '#71717a' }}>
                    총 거래
                  </Typography>
                  <Typography variant="body2" sx={{ color: '#ffffff' }}>
                    {backtestResult.totalTrades || 0} 회
                  </Typography>
                </Box>
                <Box>
                  <Typography variant="caption" sx={{ color: '#71717a' }}>
                    승률
                  </Typography>
                  <Typography variant="body2" sx={{ color: '#ffffff' }}>
                    {backtestResult.winRate?.toFixed(1)}%
                  </Typography>
                </Box>
              </Box>
            </Box>
          )}

          {/* 시그널 테이블 */}
          {signals.length > 0 && (
            <SignalTable
              data={macdData}
              interval={timeInterval}
            />
          )}
        </Box>
      </Drawer>
    </Box>
  );
};

export default MobileChartPage;

