import React, { useState, useEffect, useMemo, useRef, useCallback } from 'react';
import {
  Box,
  AppBar,
  Toolbar,
  Typography,
  IconButton,
  Select,
  MenuItem,
  FormControl,
  CircularProgress,
  Alert,
  Drawer,
  Button,
  Divider,
  List,
  ListItem,
  ListItemText,
  ListItemSecondaryAction,
  Switch,
  Chip,
} 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,
} from '@mui/icons-material';
import { Time } from 'lightweight-charts';
import { useUpbitData } from '../contexts/UpbitDataContext';
import { useAppTheme } from '../contexts/ThemeContext';
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';
import ChartToolbar, { ChartTool } from '../components/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';

/**
 * 모바일 전용 차트 페이지
 * - 간단한 UI
 * - 터치 최적화
 * - 전체 화면 차트
 */
const MobileChartPage: React.FC = () => {
  const { 
    symbol, 
    setSymbol, 
    timeInterval, 
    setTimeInterval,
    macdData,
    loading,
    error,
    fetchChartData
  } = useUpbitData();

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

  // 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 [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 [activeTool, setActiveTool] = useState<ChartTool>('crosshair');
  const [showChartToolbar, setShowChartToolbar] = useState(false);
  
  // ✅ 모든 차트 간 시간 범위 동기화
  const [sharedTimeRange, setSharedTimeRange] = useState<{ from: number; to: number } | null>(null);
  
  // ✅ 모든 차트 간 크로스헤어 동기화
  const [sharedHoverTime, setSharedHoverTime] = useState<Time | null>(null);
  
  // ✅ Throttle을 위한 타이머 ref
  const syncThrottleTimer = useRef<NodeJS.Timeout | null>(null);
  
  // ✅ 캔들차트 높이 비율 (0~1, 전체 화면 대비)
  const [candleChartHeightRatio, setCandleChartHeightRatio] = useState(0.5);
  
  // ✅ 리사이저 드래그 상태
  const [isResizing, setIsResizing] = useState(false);
  const resizerStartY = useRef<number>(0);
  const initialHeightRatio = useRef<number>(0.5);
  const containerRef = useRef<HTMLDivElement>(null);
  
  // ✅ 정확한 높이 계산 (하단 네비게이션 포함)
  const APPBAR_HEIGHT = 56; // 상단 AppBar 높이
  const BOTTOM_NAV_HEIGHT = 0; // 하단 네비게이션 높이 (모바일에서는 없음)
  const RESIZER_HEIGHT = 8; // 리사이저 높이
  const INDICATOR_TITLE_HEIGHT = 28; // 보조지표 타이틀 높이
  
  // 사용 가능한 전체 높이 (최소 400px 보장)
  const availableHeight = Math.max(400, 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(() => {
    // 초기 데이터 로드
    fetchChartData();
    
    // 전략 규칙 로드
    loadStrategyRules();
  }, []);

  // 전략 규칙 로드
  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);
  };

  // ✅ 시간 범위 변경 시 모든 차트에 적용
  // ✅ 시간 범위 변경 시 throttle 적용 (성능 최적화)
  const handleVisibleRangeChange = useCallback((from: number, to: number) => {
    // 이전 타이머 취소
    if (syncThrottleTimer.current) {
      clearTimeout(syncThrottleTimer.current);
    }
    
    // 100ms throttle로 동기화 빈도 감소
    syncThrottleTimer.current = setTimeout(() => {
      setSharedTimeRange({ from, to });
    }, 100);
  }, []);

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

  // 전체화면 토글
  const handleFullscreenToggle = () => {
    setIsFullscreen(!isFullscreen);
  };
  
  // ✅ 리사이저 드래그 시작
  const handleResizerMouseDown = (e: React.MouseEvent | React.TouchEvent) => {
    e.preventDefault();
    setIsResizing(true);
    
    const clientY = 'touches' in e ? e.touches[0].clientY : e.clientY;
    resizerStartY.current = clientY;
    initialHeightRatio.current = candleChartHeightRatio;
  };
  
  // ✅ 리사이저 드래그 중
  useEffect(() => {
    if (!isResizing) return;
    
    const handleMove = (e: MouseEvent | TouchEvent) => {
      if (!containerRef.current) return;
      
      const clientY = 'touches' in e ? (e as TouchEvent).touches[0].clientY : (e as MouseEvent).clientY;
      const deltaY = clientY - resizerStartY.current;
      const containerHeight = containerRef.current.clientHeight;
      const deltaRatio = deltaY / containerHeight;
      
      let newRatio = initialHeightRatio.current + deltaRatio;
      // 최소 30%, 최대 80%로 제한
      newRatio = Math.max(0.3, Math.min(0.8, newRatio));
      
      setCandleChartHeightRatio(newRatio);
    };
    
    const handleEnd = () => {
      setIsResizing(false);
    };
    
    document.addEventListener('mousemove', handleMove);
    document.addEventListener('mouseup', handleEnd);
    document.addEventListener('touchmove', handleMove);
    document.addEventListener('touchend', handleEnd);
    
    return () => {
      document.removeEventListener('mousemove', handleMove);
      document.removeEventListener('mouseup', handleEnd);
      document.removeEventListener('touchmove', handleMove);
      document.removeEventListener('touchend', handleEnd);
    };
  }, [isResizing]);

  // 기간 이동 (이전/다음)
  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: '거래량', 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', 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);
    console.log('🔍 [MobileChartPage] Active Indicators:', {
      total: indicators.length,
      active: activeList.length,
      activeList: activeList.map(i => i.label),
      settings: {
        volume: indicatorVisibilitySettings.volume,
        macdLine: indicatorVisibilitySettings.macdLine,
        macdHistogram: indicatorVisibilitySettings.macdHistogram,
        cci: indicatorVisibilitySettings.cci,
        obv: indicatorVisibilitySettings.obv,
        stochasticSlow: indicatorVisibilitySettings.stochasticSlow,
      }
    });
    return activeList;
  }, [indicatorVisibilitySettings]);

  // 주요 암호화폐 목록
  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: '월봉' },
  ];

  return (
    <Box
      sx={{
        width: '100vw',
        height: '100vh',
        display: 'flex',
        flexDirection: 'column',
        bgcolor: 'background.default',
        overflow: isFullscreen ? 'hidden' : 'auto',
        touchAction: 'pan-y',
        WebkitOverflowScrolling: 'touch',
      }}
    >
      {/* 상단 앱바 */}
      {!isFullscreen && (
        <AppBar position="static" elevation={1}>
          <Toolbar variant="dense" sx={{ minHeight: 48 }}>
            <IconButton
              color="inherit"
              onClick={() => setShowCryptoList(true)}
              size="small"
              sx={{ mr: 1 }}
            >
              <MenuIcon />
            </IconButton>

            {/* 종목 선택 - ComboBox로 변경 */}
            <Box sx={{ flexGrow: 1, maxWidth: 200, mr: 1 }}>
              <CryptoNameComboBox
                value={symbol}
                onChange={setSymbol}
                size="small"
                sx={{
                  bgcolor: 'rgba(255, 255, 255, 0.1)',
                  borderRadius: 1,
                  '& .MuiInputBase-root': {
                    color: 'white',
                  },
                  '& .MuiOutlinedInput-notchedOutline': {
                    borderColor: 'rgba(255, 255, 255, 0.3)',
                  },
                }}
              />
            </Box>

            {/* 간격 선택 */}
            <FormControl size="small" sx={{ minWidth: 70, mr: 1 }}>
              <Select
                value={timeInterval}
                onChange={handleIntervalChange}
                sx={{
                  color: 'white',
                  '.MuiOutlinedInput-notchedOutline': { borderColor: 'rgba(255, 255, 255, 0.3)' },
                  '&:hover .MuiOutlinedInput-notchedOutline': { borderColor: 'rgba(255, 255, 255, 0.5)' },
                  '.MuiSvgIcon-root': { color: 'white' },
                }}
              >
                {intervals.map((interval) => (
                  <MenuItem key={interval.value} value={interval.value}>
                    {interval.label}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>

            {/* 다크/라이트 모드 토글 */}
            <IconButton color="inherit" onClick={toggleTheme} size="small">
              {themeMode === 'dark' ? <Brightness7 /> : <Brightness4 />}
            </IconButton>

            {/* 새로고침 버튼 */}
            <IconButton color="inherit" onClick={handleRefresh} size="small">
              <RefreshIcon />
            </IconButton>

            {/* 보조지표 설정 버튼 */}
            <IconButton color="inherit" onClick={() => setShowIndicatorSettings(true)} size="small">
              <TuneIcon />
            </IconButton>

            {/* 시그널 테이블 버튼 */}
            <IconButton
              color="inherit"
              onClick={() => setShowSignalTable(!showSignalTable)}
              size="small"
            >
              <SignalIcon />
            </IconButton>

            {/* 차트 툴바 토글 버튼 */}
            <IconButton
              color="inherit"
              onClick={() => setShowChartToolbar(!showChartToolbar)}
              size="small"
            >
              <SettingsIcon />
            </IconButton>

            {/* 전체화면 버튼 */}
            <IconButton color="inherit" onClick={handleFullscreenToggle} size="small">
              <Fullscreen />
            </IconButton>
          </Toolbar>
        </AppBar>
      )}

      {/* 차트 영역 */}
      <Box
        ref={containerRef}
        sx={{
          position: 'relative',
          // 정확한 높이: 전체 화면 - 상단바 - 하단 네비게이션
          height: isFullscreen ? '100vh' : `${availableHeight}px`,
          display: 'flex',
          flexDirection: 'column',
          overflow: 'hidden', // ✅ 스크롤 완전 비활성화
          flex: 'none', // flex 1 제거하여 정확한 높이 유지
        }}
      >
        {/* 전체화면 모드 종료 버튼 */}
        {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>
        )}

        {/* 기간 이동 버튼 */}
        {!isFullscreen && (
          <Box
            sx={{
              position: 'absolute',
              top: 8,
              left: 8,
              zIndex: 1100,
              display: 'flex',
              gap: 1,
            }}
          >
            <IconButton
              size="small"
              onClick={() => handleNavigate('past')}
              sx={{
                bgcolor: 'background.paper',
                boxShadow: 1,
                '&:hover': { bgcolor: 'action.hover' },
              }}
            >
              <NavigateBefore />
            </IconButton>
            <IconButton
              size="small"
              onClick={() => handleNavigate('future')}
              sx={{
                bgcolor: 'background.paper',
                boxShadow: 1,
                '&:hover': { bgcolor: 'action.hover' },
              }}
            >
              <NavigateNext />
            </IconButton>
          </Box>
        )}
        {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={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
            {/* 캔들스틱 차트 */}
            <Box 
              sx={{ 
                height: `${availableHeight * candleChartHeightRatio}px`,
                position: 'relative',
                minHeight: '200px',
                flex: 'none', // 정확한 높이 유지
              }}
            >
              <CandlestickChart
                ref={chartRef}
                data={candleData}
                indicatorData={indicatorData}
                height={Math.floor(availableHeight * candleChartHeightRatio)}
                showLeftButton={false}
                showRightButton={false}
                onTimeRangeChange={() => {}}
                onCrosshairMove={handleCrosshairMove}
                onVisibleRangeChange={handleVisibleRangeChange}
                onNavigate={handleNavigate}
                externalHoverTime={sharedHoverTime}
                isMobileMode={true}
                sharedTimeRange={sharedTimeRange}
                indicatorSettings={paramSettings}
                colorSettings={colorSettings}
                activeTool={activeTool}
              />

              {/* 차트 툴바 (모바일 최적화) */}
              {!isFullscreen && showChartToolbar && (
                <Box
                  sx={{
                    position: 'absolute',
                    bottom: 8,
                    left: '50%',
                    transform: 'translateX(-50%)',
                    zIndex: 1000,
                  }}
                >
                  <ChartToolbar
                    activeTool={activeTool}
                    onToolChange={setActiveTool}
                  />
                </Box>
              )}
            </Box>

            {/* 리사이저 (드래그 핸들) */}
            {!isFullscreen && activeIndicators.length > 0 && (
              <Box
                onMouseDown={handleResizerMouseDown}
                onTouchStart={handleResizerMouseDown}
                sx={{
                  height: '8px',
                  bgcolor: isResizing ? 'primary.main' : 'divider',
                  cursor: 'ns-resize',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  transition: 'background-color 0.2s',
                  '&:hover': {
                    bgcolor: 'primary.light',
                  },
                  '&:active': {
                    bgcolor: 'primary.main',
                  },
                  zIndex: 1100,
                }}
              >
                <Box
                  sx={{
                    width: '40px',
                    height: '4px',
                    bgcolor: 'background.paper',
                    borderRadius: '2px',
                  }}
                />
              </Box>
            )}

            {/* 보조지표 차트들 - 정확한 높이 계산으로 한 화면에 모두 표시 */}
            {!isFullscreen && indicatorData && indicatorData.length > 0 && activeIndicators.length > 0 && (() => {
              // 보조지표 영역 전체 높이
              const indicatorAreaHeight = Math.max(150, availableHeight * (1 - candleChartHeightRatio) - RESIZER_HEIGHT);
              // 각 보조지표 높이 (타이틀 포함)
              const singleIndicatorHeight = Math.max(80, Math.floor(indicatorAreaHeight / activeIndicators.length));
              // 차트 영역 높이 (타이틀 제외, 최소 50px 보장)
              const chartHeight = Math.max(50, singleIndicatorHeight - INDICATOR_TITLE_HEIGHT);
              
              console.log(`[MobileChartPage] Height Calculation:`, {
                windowHeight: window.innerHeight,
                appBarHeight: APPBAR_HEIGHT,
                bottomNavHeight: BOTTOM_NAV_HEIGHT,
                availableHeight,
                candleChartHeight: availableHeight * candleChartHeightRatio,
                indicatorAreaHeight,
                activeIndicatorsCount: activeIndicators.length,
                singleIndicatorHeight,
                chartHeight,
              });
              
              return (
                <Box 
                  sx={{ 
                    height: `${indicatorAreaHeight}px`,
                    display: 'flex',
                    flexDirection: 'column',
                    overflow: 'hidden',
                    flex: 'none',
                  }}
                >
                  {activeIndicators.map((indicator, index) => (
                    <Box
                      key={indicator.key}
                      sx={{
                        height: `${singleIndicatorHeight}px`,
                        bgcolor: 'background.paper',
                        borderTop: index === 0 ? 'none' : '1px solid',
                        borderColor: 'divider',
                        display: 'flex',
                        flexDirection: 'column',
                        flex: 'none',
                        overflow: 'hidden',
                      }}
                    >
                      <Box
                        sx={{
                          display: 'flex',
                          alignItems: 'center',
                          px: 1,
                          py: 0.5,
                          borderBottom: '1px solid',
                          borderColor: 'divider',
                          bgcolor: 'action.hover',
                          height: `${INDICATOR_TITLE_HEIGHT}px`,
                          flex: 'none',
                        }}
                      >
                        <Typography variant="caption" sx={{ fontWeight: 'bold', fontSize: '11px' }}>
                          {indicator.label}
                        </Typography>
                      </Box>
                      <Box sx={{ height: `${chartHeight}px`, position: 'relative', flex: 'none', overflow: 'hidden' }}>
                        <IndicatorChart
                          type={indicator.type as any}
                          data={indicatorData}
                          height={chartHeight}
                          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>

      {/* 종목 리스트 패널 (Drawer) */}
      <Drawer
        anchor="left"
        open={showCryptoList}
        onClose={() => setShowCryptoList(false)}
      >
        <Box sx={{ width: 300, p: 2 }}>
          <Typography variant="h6" sx={{ mb: 2 }}>
            종목 선택
          </Typography>
          <Divider sx={{ mb: 2 }} />
          <CryptoListPanel
            currentSymbol={symbol}
            onSelectSymbol={handleCryptoSelect}
          />
        </Box>
      </Drawer>

      {/* 보조지표 설정 패널 (Drawer) */}
      <Drawer
        anchor="right"
        open={showIndicatorSettings}
        onClose={() => setShowIndicatorSettings(false)}
      >
        <Box sx={{ width: 300, p: 2 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
            <Typography variant="h6" sx={{ flexGrow: 1 }}>
              보조지표 설정
            </Typography>
            <IconButton size="small" onClick={() => setShowIndicatorSettings(false)}>
              <SettingsIcon />
            </IconButton>
          </Box>
          <Divider sx={{ mb: 2 }} />
          
          {/* 차트 설정 바로가기 */}
          <Box sx={{ mb: 2 }}>
            <Typography variant="subtitle2" color="text.secondary" sx={{ mb: 1 }}>
              차트 설정
            </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 }} />

          <Typography variant="subtitle2" color="text.secondary" sx={{ mb: 1 }}>
            보조지표 표시/숨김 ({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} />
                <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)}
      >
        <Box sx={{ height: '70vh', p: 2, overflowY: 'auto' }}>
          <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
            <Typography variant="h6" sx={{ flexGrow: 1 }}>
              매매 시그널
            </Typography>
            <IconButton size="small" onClick={() => setShowSignalTable(false)}>
              <FullscreenExit />
            </IconButton>
          </Box>

          {/* 전략 선택 */}
          <Box sx={{ mb: 2 }}>
            <Typography variant="subtitle2" sx={{ mb: 1 }}>
              전략 선택
            </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: 'background.paper', borderRadius: 1 }}>
              <Typography variant="subtitle2" gutterBottom>
                백테스트 결과
              </Typography>
              <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 1 }}>
                <Box>
                  <Typography variant="caption" color="text.secondary">
                    최종 잔액
                  </Typography>
                  <Typography variant="body2" fontWeight="bold">
                    {backtestResult.finalCapital?.toLocaleString()} 원
                  </Typography>
                </Box>
                <Box>
                  <Typography variant="caption" color="text.secondary">
                    수익률
                  </Typography>
                  <Typography
                    variant="body2"
                    fontWeight="bold"
                    color={backtestResult.returnRate >= 0 ? 'success.main' : 'error.main'}
                  >
                    {backtestResult.returnRate?.toFixed(2)}%
                  </Typography>
                </Box>
                <Box>
                  <Typography variant="caption" color="text.secondary">
                    총 거래
                  </Typography>
                  <Typography variant="body2">
                    {backtestResult.totalTrades || 0} 회
                  </Typography>
                </Box>
                <Box>
                  <Typography variant="caption" color="text.secondary">
                    승률
                  </Typography>
                  <Typography variant="body2">
                    {backtestResult.winRate?.toFixed(1)}%
                  </Typography>
                </Box>
              </Box>
            </Box>
          )}

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

export default MobileChartPage;

