import React, { useState, useEffect, useCallback, useMemo } from 'react';
import {
  Box,
  Typography,
  Button,
  Chip,
  FormControlLabel,
  Switch,
  Slider,
  CircularProgress,
  Alert,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Tooltip,
  LinearProgress,
  Paper,
  Grid,
} from '@mui/material';
import {
  Search as SearchIcon,
  Refresh as RefreshIcon,
  ExpandMore as ExpandMoreIcon,
  TrendingUp as TrendingUpIcon,
  ShowChart as ChartIcon,
  FilterList as FilterIcon,
} from '@mui/icons-material';
import { useAppTheme } from '../contexts/ThemeContext';
import CandlestickChart from '../components/CandlestickChart';
import {
  RisingStock,
  RisingStockSearchRequest,
  searchRisingStocks,
  getFilterDefaults,
  triggerScan,
  getScanStatus,
  DEFAULT_SEARCH_REQUEST,
} from '../services/risingStockApi';
import { fetchCandleData } from '../services/patternApi';
import { CandleData } from '../services/backtestApi';

/**
 * 상승 종목 선정 페이지
 * 6단계 필터링 + 종합 스코어링 기반 상승 종목 자동 선정
 */
const RisingStocksPage: React.FC = () => {
  const { themeMode } = useAppTheme();
  const isDark = themeMode === 'dark';
  
  // 상태 관리
  const [stocks, setStocks] = useState<RisingStock[]>([]);
  const [selectedStock, setSelectedStock] = useState<RisingStock | null>(null);
  const [chartData, setChartData] = useState<CandleData[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isLoadingChart, setIsLoadingChart] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isScanning, setIsScanning] = useState(false);
  
  // 검색 조건 상태
  const [searchRequest, setSearchRequest] = useState<RisingStockSearchRequest>(DEFAULT_SEARCH_REQUEST);
  const [expandedFilter, setExpandedFilter] = useState<string | false>('stage2'); // 상승추세 판별이 핵심
  
  // 필터 그룹 정의 (단계별 상승추세 검증)
  // 더 많은 조건을 충족할수록 → 더 강한 상승추세
  const filterGroups = useMemo(() => [
    {
      id: 'stage1',
      name: '1단계: 하락추세 제거',
      icon: '🛡️',
      description: '손실 위험 최소화',
      filters: [
        { key: 'enableCloseMa60Filter', name: '가격 > MA60', description: '현재가가 60일 이동평균 위 (기본 ON 권장)' },
        { key: 'enableMa20Ma60Filter', name: 'MA20 > MA60', description: '단기선이 중기선 위 (기본 ON 권장)' },
        { key: 'enableAdxDiFilter', name: 'ADX 하락추세 제거', description: '강한 하락추세 종목 제외 (선택)' },
        { key: 'enableHigh120Filter', name: '120일 고점 대비', description: '급락 종목 제외 (신규 코인은 OFF)' },
      ],
    },
    {
      id: 'stage2',
      name: '2단계: 상승추세 판별',
      icon: '📈',
      description: '실제 상승 방향 확인',
      filters: [
        { key: 'enableMaSlopeFilter', name: 'MA20 기울기 ↑', description: '20일선 우상향 (ON 권장)' },
        { key: 'enableMacdFilter', name: 'MACD > Signal', description: '모멘텀 상승 신호 (ON 권장)' },
        { key: 'enableMaAlignmentFilter', name: 'MA 정배열', description: 'MA20>MA60>MA120 (데이터 충분 시)' },
        { key: 'enableRsiFilter', name: 'RSI 35~75', description: '적정 RSI 범위 (선택)' },
      ],
    },
    {
      id: 'stage3',
      name: '3단계: 모멘텀 확인',
      icon: '🚀',
      description: '상승 강도 검증',
      filters: [
        { key: 'enableBullishCandleFilter', name: '양봉 (상승 마감)', description: '당일 양봉 종목만 (ON 권장)' },
        { key: 'enableMinChangeRateFilter', name: '최소 등락률', description: '일정 % 이상 상승 종목 (선택)' },
        { key: 'enableVolume20dFilter', name: '20일 거래량 돌파', description: '평균의 2~3배 거래량 (선택)' },
        { key: 'enableVolume5dFilter', name: '5일 거래량 + 양봉', description: '단기 거래량 급증 (선택)' },
      ],
    },
    {
      id: 'stage4',
      name: '4단계: 추가 확인',
      icon: '🔍',
      description: '주식 전용 / 고급 필터',
      filters: [
        { key: 'enableForeignNetFilter', name: '외국인 순매수', description: '외국인 10억+ 순매수 (주식)' },
        { key: 'enableInstNetFilter', name: '기관 순매수', description: '기관 5억+ 순매수 (주식)' },
        { key: 'enableProgramNetFilter', name: '프로그램 순매수', description: '프로그램 매매 양수 (주식)' },
        { key: 'enableTradeStrengthFilter', name: '체결강도 ≥140%', description: '강한 매수세 (초단타)' },
        { key: 'enableBidAskRatioFilter', name: '매수잔량 우위', description: '호가창 매수 우세 (초단타)' },
      ],
    },
  ], []);
  
  // 초기 로드
  useEffect(() => {
    handleSearch();
  }, []);
  
  // 검색 실행
  const handleSearch = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    
    try {
      const result = await searchRisingStocks(searchRequest);
      setStocks(result);
      
      if (result.length > 0 && !selectedStock) {
        handleSelectStock(result[0]);
      }
    } catch (err) {
      setError('검색 중 오류가 발생했습니다.');
      console.error(err);
    } finally {
      setIsLoading(false);
    }
  }, [searchRequest, selectedStock]);
  
  // 종목 선택
  const handleSelectStock = useCallback(async (stock: RisingStock) => {
    setSelectedStock(stock);
    setIsLoadingChart(true);
    
    try {
      const response = await fetchCandleData(stock.code, '1d', 200);
      if (response.success && response.data.length > 0) {
        const convertedData: CandleData[] = response.data.map(candle => ({
          time: candle.time,
          open: candle.open,
          high: candle.high,
          low: candle.low,
          close: candle.close,
          volume: candle.volume || 0,
        }));
        setChartData(convertedData);
      }
    } catch (err) {
      console.error('차트 데이터 로드 실패:', err);
    } finally {
      setIsLoadingChart(false);
    }
  }, []);
  
  // 필터 토글
  const handleFilterToggle = useCallback((key: string) => {
    setSearchRequest(prev => ({
      ...prev,
      [key]: !prev[key as keyof RisingStockSearchRequest],
    }));
  }, []);
  
  // 수동 스캔
  const handleManualScan = useCallback(async () => {
    setIsScanning(true);
    try {
      await triggerScan();
      // 3초 후 결과 조회
      setTimeout(() => {
        handleSearch();
        setIsScanning(false);
      }, 3000);
    } catch (err) {
      setIsScanning(false);
    }
  }, [handleSearch]);
  
  // 점수 색상
  const getScoreColor = (score: number) => {
    if (score >= 80) return '#22c55e';
    if (score >= 60) return '#f59e0b';
    return '#ef4444';
  };
  
  // 신호 강도 색상
  const getSignalColor = (strength: string) => {
    switch (strength) {
      case 'STRONG': return '#22c55e';
      case 'MEDIUM': return '#f59e0b';
      default: return '#71717a';
    }
  };
  
  // 패널 스타일
  const panelStyle = {
    bgcolor: isDark ? '#18181b' : '#ffffff',
    borderColor: isDark ? '#27272a' : '#e0e0e0',
  };

  return (
    <Grid container spacing={2}>
      {/* 상단 툴바 카드 */}
      <Grid item xs={12}>
        <Paper elevation={3} sx={{ p: 2 }}>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 2 }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
              <TrendingUpIcon sx={{ fontSize: 24, color: '#22c55e' }} />
              <Typography variant="h6" sx={{ fontWeight: 600 }}>
                추세검색
              </Typography>
              {stocks.length > 0 && (
                <Chip 
                  label={`${stocks.length}개 발견`} 
                  size="small" 
                  color="success"
                />
              )}
            </Box>
            <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>
              <Button
                variant="contained"
                size="small"
                startIcon={isLoading ? <CircularProgress size={14} color="inherit" /> : <SearchIcon />}
                onClick={handleSearch}
                disabled={isLoading}
              >
                검색
              </Button>
              <Button
                variant="outlined"
                size="small"
                startIcon={isScanning ? <CircularProgress size={14} /> : <RefreshIcon />}
                onClick={handleManualScan}
                disabled={isScanning}
              >
                {isScanning ? '스캔 중...' : '스캔'}
              </Button>
            </Box>
          </Box>
        </Paper>
      </Grid>

      {/* 3컬럼 레이아웃 */}
      <Grid item xs={12}>
        <Box sx={{
          display: 'grid',
          gridTemplateColumns: { xs: '1fr', md: '300px 1fr 380px' },
          height: 'calc(100vh - 280px)',
          minHeight: 500,
          gap: 2,
        }}>
          {/* 왼쪽 패널 - 검색 필터 */}
          <Paper elevation={2} sx={{ display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
            {/* 헤더 */}
            <Box sx={{ 
              p: 1.5, 
              borderBottom: `1px solid ${isDark ? '#27272a' : '#e0e0e0'}`,
              display: 'flex',
              alignItems: 'center',
              gap: 1,
              bgcolor: isDark ? '#1f1f26' : '#f5f5f5',
            }}>
              <FilterIcon sx={{ fontSize: 18, color: isDark ? '#a1a1aa' : '#666' }} />
              <Typography sx={{ fontSize: '13px', fontWeight: 600 }}>
                검색 필터
              </Typography>
            </Box>
        
        {/* 필터 목록 */}
        <Box sx={{ flex: 1, overflow: 'auto', p: 1 }}>
          {filterGroups.map((group) => (
            <Accordion
              key={group.id}
              expanded={expandedFilter === group.id}
              onChange={(_, isExpanded) => setExpandedFilter(isExpanded ? group.id : false)}
              sx={{
                bgcolor: isDark ? '#1f1f26' : '#f5f5f5',
                '&:before': { display: 'none' },
                mb: 1,
                borderRadius: 1,
                overflow: 'hidden',
              }}
            >
              <AccordionSummary
                expandIcon={<ExpandMoreIcon sx={{ fontSize: 18 }} />}
                sx={{
                  minHeight: 48,
                  '& .MuiAccordionSummary-content': { my: 0.5, flexDirection: 'column', alignItems: 'flex-start' },
                }}
              >
                <Typography sx={{ fontSize: '12px', fontWeight: 600, display: 'flex', alignItems: 'center', gap: 1 }}>
                  {group.icon} {group.name}
                </Typography>
                {'description' in group && (
                  <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888', mt: 0.25 }}>
                    {(group as { description?: string }).description}
                  </Typography>
                )}
              </AccordionSummary>
              <AccordionDetails sx={{ p: 1.5, pt: 0.5 }}>
                {group.filters.map((filter) => (
                  <Tooltip key={filter.key} title={filter.description} arrow placement="right">
                    <FormControlLabel
                      control={
                        <Switch
                          size="small"
                          checked={!!searchRequest[filter.key as keyof RisingStockSearchRequest]}
                          onChange={() => handleFilterToggle(filter.key)}
                          color="success"
                        />
                      }
                      label={
                        <Typography sx={{ 
                          fontSize: '11px',
                          color: searchRequest[filter.key as keyof RisingStockSearchRequest] 
                            ? (isDark ? '#22c55e' : '#16a34a') 
                            : (isDark ? '#a1a1aa' : '#666'),
                        }}>
                          {filter.name}
                        </Typography>
                      }
                      sx={{ 
                        display: 'flex', 
                        mb: 0.5,
                        '& .MuiFormControlLabel-label': { flex: 1 },
                      }}
                    />
                  </Tooltip>
                ))}
              </AccordionDetails>
            </Accordion>
          ))}
          
          {/* 추가 설정 */}
          <Box sx={{ p: 1.5, bgcolor: isDark ? '#1f1f26' : '#f5f5f5', borderRadius: 1 }}>
            <Typography sx={{ fontSize: '11px', fontWeight: 600, mb: 1, color: isDark ? '#a1a1aa' : '#666' }}>
              ⚙️ 검색 설정
            </Typography>
            
            <Box sx={{ mb: 2 }}>
              <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888', mb: 0.5 }}>
                최대 결과 수: {searchRequest.maxResults}
              </Typography>
              <Slider
                value={searchRequest.maxResults || 20}
                onChange={(_, v) => setSearchRequest(prev => ({ ...prev, maxResults: v as number }))}
                min={5}
                max={50}
                step={5}
                size="small"
              />
            </Box>
            
            <Box>
              <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888', mb: 0.5 }}>
                최소 점수: {searchRequest.minTotalScore}점
              </Typography>
              <Slider
                value={searchRequest.minTotalScore || 0}
                onChange={(_, v) => setSearchRequest(prev => ({ ...prev, minTotalScore: v as number }))}
                min={0}
                max={100}
                step={5}
                size="small"
              />
            </Box>
          </Box>
        </Box>
        
          </Paper>
      
          {/* 중앙 패널 - 검색 결과 목록 */}
          <Paper elevation={2} sx={{ display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
            {/* 헤더 */}
            <Box sx={{ 
              p: 1.5, 
              borderBottom: `1px solid ${isDark ? '#27272a' : '#e0e0e0'}`,
              display: 'flex',
              alignItems: 'center',
              gap: 1,
              bgcolor: isDark ? '#1f1f26' : '#f5f5f5',
            }}>
              <TrendingUpIcon sx={{ fontSize: 18, color: '#22c55e' }} />
              <Typography sx={{ fontSize: '13px', fontWeight: 600 }}>
                검색 결과
              </Typography>
            </Box>
        
        {/* 로딩 */}
        {isLoading && <LinearProgress />}
        
        {/* 에러 */}
        {error && (
          <Alert severity="error" sx={{ m: 1 }}>
            {error}
          </Alert>
        )}
        
        {/* 결과 목록 */}
        <Box sx={{ flex: 1, overflow: 'auto', p: 1 }}>
          {stocks.length === 0 && !isLoading ? (
            <Box sx={{ textAlign: 'center', py: 4 }}>
              <Typography sx={{ fontSize: '32px', mb: 1 }}>📊</Typography>
              <Typography sx={{ fontSize: '13px', color: isDark ? '#52525b' : '#999' }}>
                조건에 맞는 종목이 없습니다
              </Typography>
            </Box>
          ) : (
            stocks.map((stock, index) => (
              <Box
                key={stock.code}
                onClick={() => handleSelectStock(stock)}
                sx={{
                  p: 1.5,
                  mb: 1,
                  borderRadius: 1,
                  border: `2px solid ${selectedStock?.code === stock.code ? '#3b82f6' : (isDark ? '#27272a' : '#e0e0e0')}`,
                  bgcolor: selectedStock?.code === stock.code 
                    ? (isDark ? 'rgba(59, 130, 246, 0.15)' : 'rgba(59, 130, 246, 0.1)') 
                    : (isDark ? '#1f1f26' : '#f5f5f5'),
                  cursor: 'pointer',
                  transition: 'all 0.15s',
                  '&:hover': {
                    borderColor: '#3b82f6',
                  },
                }}
              >
                {/* 상단: 순위, 종목명, 점수 */}
                <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 1 }}>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Box sx={{
                      width: 24,
                      height: 24,
                      borderRadius: '50%',
                      bgcolor: index < 3 ? '#f59e0b' : (isDark ? '#3f3f46' : '#d0d0d0'),
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      fontSize: '11px',
                      fontWeight: 700,
                      color: index < 3 ? '#fff' : (isDark ? '#a1a1aa' : '#666'),
                    }}>
                      {stock.ranking || index + 1}
                    </Box>
                    <Box>
                      <Typography sx={{ fontSize: '13px', fontWeight: 600 }}>
                        {stock.code.split('-')[1]}
                      </Typography>
                      <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>
                        {stock.name}
                      </Typography>
                    </Box>
                  </Box>
                  <Box sx={{ textAlign: 'right' }}>
                    <Typography sx={{ 
                      fontSize: '18px', 
                      fontWeight: 700, 
                      color: getScoreColor(stock.totalScore ?? 0),
                      lineHeight: 1,
                    }}>
                      {stock.totalScore?.toFixed(1) ?? '0.0'}
                    </Typography>
                    <Chip
                      label={stock.signalStrength || 'WEAK'}
                      size="small"
                      sx={{
                        height: 16,
                        fontSize: '9px',
                        bgcolor: getSignalColor(stock.signalStrength || 'WEAK') + '20',
                        color: getSignalColor(stock.signalStrength || 'WEAK'),
                      }}
                    />
                  </Box>
                </Box>
                
                {/* 중단: 가격, 등락률, 거래량 비율 */}
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 1 }}>
                  <Typography sx={{ fontSize: '12px', fontWeight: 500 }}>
                    ₩{stock.currentPrice != null ? (
                      stock.currentPrice >= 1000 
                        ? stock.currentPrice.toLocaleString() 
                        : stock.currentPrice >= 1 
                          ? stock.currentPrice.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
                          : stock.currentPrice.toFixed(8).replace(/\.?0+$/, '')
                    ) : '-'}
                  </Typography>
                  <Typography sx={{ 
                    fontSize: '12px', 
                    fontWeight: 600,
                    color: (stock.changeRate ?? 0) >= 0 ? '#22c55e' : '#ef4444',
                  }}>
                    {(stock.changeRate ?? 0) >= 0 ? '+' : ''}{stock.changeRate?.toFixed(2) ?? '0.00'}%
                  </Typography>
                  {stock.volumeRatio && (
                    <Typography sx={{ 
                      fontSize: '10px', 
                      color: isDark ? '#a1a1aa' : '#666',
                      bgcolor: isDark ? '#27272a' : '#e5e5e5',
                      px: 0.5,
                      borderRadius: 0.5,
                    }}>
                      거래량 {stock.volumeRatio.toFixed(1)}배
                    </Typography>
                  )}
                </Box>
                
                {/* 하단: 점수 바 (각 점수별 시각적 표시) */}
                <Box sx={{ display: 'flex', gap: 0.5 }}>
                  <Tooltip title={`추세: ${stock.trendScore?.toFixed(1) ?? 0}점`} arrow>
                    <Box sx={{ flex: 1, height: 6, bgcolor: isDark ? '#27272a' : '#e0e0e0', borderRadius: 2, overflow: 'hidden' }}>
                      <Box sx={{ width: `${Math.min(stock.trendScore ?? 0, 100)}%`, height: '100%', bgcolor: '#3b82f6', transition: 'width 0.3s' }} />
                    </Box>
                  </Tooltip>
                  <Tooltip title={`거래량: ${stock.volumeScore?.toFixed(1) ?? 0}점`} arrow>
                    <Box sx={{ flex: 1, height: 6, bgcolor: isDark ? '#27272a' : '#e0e0e0', borderRadius: 2, overflow: 'hidden' }}>
                      <Box sx={{ width: `${Math.min(stock.volumeScore ?? 0, 100)}%`, height: '100%', bgcolor: '#22c55e', transition: 'width 0.3s' }} />
                    </Box>
                  </Tooltip>
                  <Tooltip title={`수급: ${stock.flowScore?.toFixed(1) ?? 0}점`} arrow>
                    <Box sx={{ flex: 1, height: 6, bgcolor: isDark ? '#27272a' : '#e0e0e0', borderRadius: 2, overflow: 'hidden' }}>
                      <Box sx={{ width: `${Math.min(stock.flowScore ?? 0, 100)}%`, height: '100%', bgcolor: '#f59e0b', transition: 'width 0.3s' }} />
                    </Box>
                  </Tooltip>
                  <Tooltip title={`모멘텀: ${stock.momentumScore?.toFixed(1) ?? 0}점`} arrow>
                    <Box sx={{ flex: 1, height: 6, bgcolor: isDark ? '#27272a' : '#e0e0e0', borderRadius: 2, overflow: 'hidden' }}>
                      <Box sx={{ width: `${Math.min(stock.momentumScore ?? 0, 100)}%`, height: '100%', bgcolor: '#a855f7', transition: 'width 0.3s' }} />
                    </Box>
                  </Tooltip>
                </Box>
                
                {/* 단계 통과 표시 */}
                <Box sx={{ display: 'flex', gap: 0.5, mt: 1 }}>
                  <Chip label="1" size="small" sx={{ height: 16, fontSize: '9px', bgcolor: stock.passStage1 ? '#22c55e20' : '#ef444420', color: stock.passStage1 ? '#22c55e' : '#ef4444' }} />
                  <Chip label="2" size="small" sx={{ height: 16, fontSize: '9px', bgcolor: stock.passStage2 ? '#22c55e20' : '#ef444420', color: stock.passStage2 ? '#22c55e' : '#ef4444' }} />
                  <Chip label="3" size="small" sx={{ height: 16, fontSize: '9px', bgcolor: stock.passStage3 ? '#22c55e20' : '#ef444420', color: stock.passStage3 ? '#22c55e' : '#ef4444' }} />
                  <Chip label="4" size="small" sx={{ height: 16, fontSize: '9px', bgcolor: stock.passStage4 ? '#22c55e20' : '#ef444420', color: stock.passStage4 ? '#22c55e' : '#ef4444' }} />
                </Box>
              </Box>
            ))
          )}
            </Box>
          </Paper>
      
          {/* 오른쪽 패널 - 차트 */}
          <Paper elevation={2} sx={{ display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
            {/* 헤더 */}
            <Box sx={{ 
              p: 1.5, 
              borderBottom: `1px solid ${isDark ? '#27272a' : '#e0e0e0'}`,
              display: 'flex',
              alignItems: 'center',
              gap: 1,
              bgcolor: isDark ? '#1f1f26' : '#f5f5f5',
            }}>
              <ChartIcon sx={{ fontSize: 18 }} />
              <Typography sx={{ fontSize: '13px', fontWeight: 600 }}>
                {selectedStock ? selectedStock.code : '차트'}
              </Typography>
              {selectedStock && (
                <Typography sx={{ fontSize: '11px', color: isDark ? '#71717a' : '#888' }}>
                  {selectedStock.name}
                </Typography>
              )}
            </Box>
        
        {/* 차트 영역 */}
        <Box sx={{ flex: 1, p: 2, minHeight: 300 }}>
          {isLoadingChart ? (
            <Box sx={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <CircularProgress />
            </Box>
          ) : chartData.length > 0 ? (
            <CandlestickChart
              data={chartData}
              height={Math.max(400, window.innerHeight - 350)}
            />
          ) : (
            <Box sx={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 2 }}>
              <Typography sx={{ fontSize: '48px' }}>📈</Typography>
              <Typography sx={{ fontSize: '13px', color: isDark ? '#52525b' : '#999' }}>
                종목을 선택하면 차트가 표시됩니다
              </Typography>
            </Box>
          )}
        </Box>
        
        {/* 종목 상세 정보 */}
        {selectedStock && (
          <Box sx={{ 
            p: 2, 
            borderTop: `1px solid ${isDark ? '#27272a' : '#e0e0e0'}`,
            bgcolor: isDark ? '#1f1f26' : '#f5f5f5',
          }}>
            <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 1 }}>
              <Box sx={{ p: 1, bgcolor: isDark ? '#27272a' : '#e0e0e0', borderRadius: 1 }}>
                <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>RSI</Typography>
                <Typography sx={{ fontSize: '13px', fontWeight: 600 }}>{selectedStock.rsi?.toFixed(1) || '-'}</Typography>
              </Box>
              <Box sx={{ p: 1, bgcolor: isDark ? '#27272a' : '#e0e0e0', borderRadius: 1 }}>
                <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>MACD</Typography>
                <Typography sx={{ fontSize: '13px', fontWeight: 600 }}>{selectedStock.macd?.toFixed(2) || '-'}</Typography>
              </Box>
              <Box sx={{ p: 1, bgcolor: isDark ? '#27272a' : '#e0e0e0', borderRadius: 1 }}>
                <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>거래량 비율</Typography>
                <Typography sx={{ fontSize: '13px', fontWeight: 600 }}>{selectedStock.volumeRatio?.toFixed(1) || '-'}배</Typography>
              </Box>
              <Box sx={{ p: 1, bgcolor: isDark ? '#27272a' : '#e0e0e0', borderRadius: 1 }}>
                <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>총점</Typography>
                <Typography sx={{ fontSize: '13px', fontWeight: 600, color: getScoreColor(selectedStock.totalScore) }}>
                  {selectedStock.totalScore?.toFixed(1)}점
                </Typography>
              </Box>
            </Box>
          </Box>
        )}
          </Paper>
        </Box>
      </Grid>
    </Grid>
  );
};

export default RisingStocksPage;

