import React, { memo } from "react";
import {
  Box,
  Typography,
  Dialog,
  DialogTitle,
  DialogContent,
  IconButton,
  Chip,
  useTheme,
} from "@mui/material";
import { Close as CloseIcon } from "@mui/icons-material";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  ResponsiveContainer,
  ReferenceLine,
  ComposedChart,
  Bar,
  Cell,
  ReferenceDot,
} from "recharts";
import DraggablePaper from "./DraggablePaper";
import type { TradeRecord, BacktestResult } from "../services/backtestApi";

export type TradeSignalDetailDialogProps = {
  open: boolean;
  trade: TradeRecord | null;
  backtestResult: BacktestResult | null;
  onClose: () => void;
};

function TradeSignalDetailDialogInner({
  open,
  trade,
  backtestResult,
  onClose,
}: TradeSignalDetailDialogProps) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  const normalizeTimeKey = (v?: string | null): string => {
    if (!v) return '';
    const s = v.replace(' ', 'T');
    // 초/밀리초 차이를 흡수하기 위해 분 단위까지 비교
    return s.length >= 16 ? s.slice(0, 16) : s;
  };

  return (
      <Dialog
        open={open}
        onClose={onClose}
        maxWidth="sm"
        fullWidth
        scroll="paper"
        hideBackdrop={true} // ✅ 백드랍 제거 - 일반 팝업으로 동작
        disableScrollLock={true} // ✅ 배경 스크롤 허용
        PaperComponent={DraggablePaper} // ✅ 드래그 가능한 Paper 사용
        sx={{
          zIndex: 9999, // ✅ 최상위 레이어로 설정
          pointerEvents: 'none', // ✅ Dialog 자체는 클릭 무시
          '& .MuiDialog-container': {
            pointerEvents: 'none', // ✅ container도 클릭 무시
            alignItems: 'flex-start', // ✅ 상단 정렬로 변경
          },
        }}
        PaperProps={{
          sx: {
            bgcolor: isDark ? '#1a1b2e' : '#fff',
            color: isDark ? '#e0e0e0' : '#333',
            borderRadius: 2,
            border: isDark ? '2px solid rgba(80, 100, 160, 0.5)' : '1px solid #ddd',
            maxHeight: '75vh',
            width: '600px',
            pointerEvents: 'auto', // ✅ Paper만 클릭 가능
            boxShadow: '0 8px 32px rgba(0, 0, 0, 0.3)', // ✅ 그림자 추가로 더 잘 보이게
          }
        }}
      >
        {/* ✅ 통일된 파란색 타이틀바 */}
        <DialogTitle sx={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          bgcolor: '#1976d2',
          color: '#fff',
          py: 1.2,
        }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
            <Typography variant="h6" sx={{ fontWeight: 600, fontSize: '16px', color: '#fff' }}>
              {trade?.tradeType === 'BUY' ? '📈 매수 신호 상세' : '📉 매도 신호 상세'}
            </Typography>
          </Box>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
            <Typography variant="caption" sx={{ color: '#fff', fontSize: '13px' }}>
              {trade?.timestamp}
            </Typography>
            <IconButton 
              onClick={() => onClose()} 
              size="small" 
              sx={{ color: '#fff' }}
            >
              <CloseIcon />
            </IconButton>
          </Box>
        </DialogTitle>
        <DialogContent sx={{ 
          pt: 2, 
          pb: 2,
          overflowY: 'auto',
          // ✅ 스크롤바 스타일 개선
          '&::-webkit-scrollbar': {
            width: '8px',
          },
          '&::-webkit-scrollbar-track': {
            background: isDark ? 'rgba(30, 35, 50, 0.5)' : '#f1f1f1',
            borderRadius: '4px',
          },
          '&::-webkit-scrollbar-thumb': {
            background: isDark ? 'rgba(80, 100, 160, 0.5)' : '#888',
            borderRadius: '4px',
            '&:hover': {
              background: isDark ? 'rgba(80, 100, 160, 0.7)' : '#555',
            },
          },
        }}>
          {trade && (
            <Box>
              {/* 기본 거래 정보 */}
              <Box sx={{
                mb: 2,
                p: 2,
                bgcolor: isDark ? 'rgba(30, 35, 50, 0.7)' : '#f5f5f5',
                borderRadius: 1,
                border: isDark ? '1px solid rgba(80, 100, 160, 0.2)' : 'none',
              }}>
                <Typography sx={{ fontWeight: 600, mb: 1.5, fontSize: '13px', color: isDark ? '#a1a1aa' : '#666' }}>
                  📊 거래 정보
                </Typography>
                <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 1.5 }}>
                  <Box>
                    <Typography sx={{ fontSize: '11px', color: isDark ? '#71717a' : '#999' }}>체결가</Typography>
                    <Typography sx={{ fontWeight: 600, fontSize: '14px' }}>₩{trade.price?.toLocaleString()}</Typography>
                  </Box>
                  <Box>
                    <Typography sx={{ fontSize: '11px', color: isDark ? '#71717a' : '#999' }}>수량</Typography>
                    <Typography sx={{ fontWeight: 600, fontSize: '14px' }}>{trade.quantity?.toFixed(6)}</Typography>
                  </Box>
                  <Box>
                    <Typography sx={{ fontSize: '11px', color: isDark ? '#71717a' : '#999' }}>거래금액</Typography>
                    <Typography sx={{ fontWeight: 600, fontSize: '14px' }}>₩{trade.totalAmount?.toLocaleString()}</Typography>
                  </Box>
                  <Box>
                    <Typography sx={{ fontSize: '11px', color: isDark ? '#71717a' : '#999' }}>수수료</Typography>
                    <Typography sx={{ fontWeight: 600, fontSize: '14px' }}>₩{trade.commission?.toLocaleString()}</Typography>
                  </Box>
                  {trade.tradeType === 'SELL' && (
                    <>
                      <Box>
                        <Typography sx={{ fontSize: '11px', color: isDark ? '#71717a' : '#999' }}>손익</Typography>
                        <Typography sx={{
                          fontWeight: 600,
                          fontSize: '14px',
                          color: (trade.profitLoss ?? 0) >= 0 ? '#22c55e' : '#ef4444',
                        }}>
                          {(trade.profitLoss ?? 0) >= 0 ? '+' : ''}₩{trade.profitLoss?.toLocaleString()}
                        </Typography>
                      </Box>
                      <Box>
                        <Typography sx={{ fontSize: '11px', color: isDark ? '#71717a' : '#999' }}>수익률</Typography>
                        <Typography sx={{
                          fontWeight: 600,
                          fontSize: '14px',
                          color: (trade.returnRate ?? 0) >= 0 ? '#22c55e' : '#ef4444',
                        }}>
                          {(trade.returnRate ?? 0) >= 0 ? '+' : ''}{trade.returnRate?.toFixed(2)}%
                        </Typography>
                      </Box>
                    </>
                  )}
                </Box>
              </Box>

              {/* 캔들 차트 정보 (OHLCV) */}
              {(trade.open || trade.high || trade.low || trade.close) && (
                <Box sx={{
                  mb: 2,
                  p: 2,
                  bgcolor: isDark ? 'rgba(30, 35, 50, 0.7)' : '#f5f5f5',
                  borderRadius: 1,
                  border: isDark ? '1px solid rgba(80, 100, 160, 0.2)' : 'none',
                }}>
                  <Typography sx={{ fontWeight: 600, mb: 1.5, fontSize: '13px', color: isDark ? '#a1a1aa' : '#666' }}>
                    🕯️ 해당 시점 캔들 정보
                  </Typography>
                  <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 1 }}>
                    <Box sx={{ textAlign: 'center', p: 1, bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff', borderRadius: 1 }}>
                      <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#999' }}>시가 (O)</Typography>
                      <Typography sx={{ fontWeight: 600, fontSize: '12px', color: isDark ? '#e0e0e0' : '#333' }}>
                        ₩{trade.open?.toLocaleString()}
                      </Typography>
                    </Box>
                    <Box sx={{ textAlign: 'center', p: 1, bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff', borderRadius: 1 }}>
                      <Typography sx={{ fontSize: '10px', color: '#ef4444' }}>고가 (H)</Typography>
                      <Typography sx={{ fontWeight: 600, fontSize: '12px', color: '#ef4444' }}>
                        ₩{trade.high?.toLocaleString()}
                      </Typography>
                    </Box>
                    <Box sx={{ textAlign: 'center', p: 1, bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff', borderRadius: 1 }}>
                      <Typography sx={{ fontSize: '10px', color: '#3b82f6' }}>저가 (L)</Typography>
                      <Typography sx={{ fontWeight: 600, fontSize: '12px', color: '#3b82f6' }}>
                        ₩{trade.low?.toLocaleString()}
                      </Typography>
                    </Box>
                    <Box sx={{ textAlign: 'center', p: 1, bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff', borderRadius: 1 }}>
                      <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#999' }}>종가 (C)</Typography>
                      <Typography sx={{ fontWeight: 600, fontSize: '12px', color: isDark ? '#e0e0e0' : '#333' }}>
                        ₩{trade.close?.toLocaleString()}
                      </Typography>
                    </Box>
                    <Box sx={{ textAlign: 'center', p: 1, bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff', borderRadius: 1 }}>
                      <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#999' }}>거래량</Typography>
                      <Typography sx={{ fontWeight: 600, fontSize: '12px', color: isDark ? '#e0e0e0' : '#333' }}>
                        {trade.volume?.toLocaleString(undefined, { maximumFractionDigits: 2 })}
                      </Typography>
                    </Box>
                  </Box>
                </Box>
              )}

              {/* 주요 지표 스냅샷 */}
              {trade.indicators && (
                <Box sx={{
                  mb: 2,
                  p: 2,
                  bgcolor: isDark ? 'rgba(30, 35, 50, 0.7)' : '#f5f5f5',
                  borderRadius: 1,
                  border: isDark ? '1px solid rgba(80, 100, 160, 0.2)' : 'none',
                }}>
                  <Typography sx={{ fontWeight: 600, mb: 1.5, fontSize: '13px', color: isDark ? '#a1a1aa' : '#666' }}>
                    📈 해당 시점 주요 지표
                  </Typography>
                  <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 1.5 }}>
                    {/* 이동평균선 */}
                    <Box sx={{ p: 1.5, bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff', borderRadius: 1 }}>
                      <Typography sx={{ fontSize: '11px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 0.5 }}>이동평균선</Typography>
                      <Box sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#999' }}>
                        {trade.indicators.ma10 && <Box>MA10: ₩{trade.indicators.ma10.toLocaleString()}</Box>}
                        {trade.indicators.ma20 && <Box>MA20: ₩{trade.indicators.ma20.toLocaleString()}</Box>}
                        {trade.indicators.ma60 && <Box>MA60: ₩{trade.indicators.ma60.toLocaleString()}</Box>}
                      </Box>
                    </Box>

                    {/* MACD */}
                    <Box sx={{ p: 1.5, bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff', borderRadius: 1 }}>
                      <Typography sx={{ fontSize: '11px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 0.5 }}>MACD</Typography>
                      <Box sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#999' }}>
                        {trade.indicators.macdLine !== undefined && <Box>MACD: {trade.indicators.macdLine?.toFixed(2)}</Box>}
                        {trade.indicators.macdSignal !== undefined && <Box>Signal: {trade.indicators.macdSignal?.toFixed(2)}</Box>}
                        {trade.indicators.macdHistogram !== undefined && (
                          <Box sx={{ color: (trade.indicators.macdHistogram ?? 0) >= 0 ? '#22c55e' : '#ef4444' }}>
                            Histogram: {trade.indicators.macdHistogram?.toFixed(2)}
                          </Box>
                        )}
                      </Box>
                    </Box>

                    {/* Stochastic */}
                    <Box sx={{ p: 1.5, bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff', borderRadius: 1 }}>
                      <Typography sx={{ fontSize: '11px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 0.5 }}>Stochastic</Typography>
                      <Box sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#999' }}>
                        {trade.indicators.stochK !== undefined && <Box>%K: {trade.indicators.stochK?.toFixed(2)}</Box>}
                        {trade.indicators.stochD !== undefined && <Box>%D: {trade.indicators.stochD?.toFixed(2)}</Box>}
                      </Box>
                    </Box>

                    {/* RSI */}
                    {trade.indicators.rsi !== undefined && (
                      <Box sx={{ p: 1.5, bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff', borderRadius: 1 }}>
                        <Typography sx={{ fontSize: '11px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 0.5 }}>RSI</Typography>
                        <Typography sx={{
                          fontSize: '14px',
                          fontWeight: 600,
                          color: (trade.indicators.rsi ?? 50) > 70 ? '#ef4444' : (trade.indicators.rsi ?? 50) < 30 ? '#22c55e' : (isDark ? '#e0e0e0' : '#333')
                        }}>
                          {trade.indicators.rsi?.toFixed(2)}
                        </Typography>
                      </Box>
                    )}

                    {/* ADX */}
                    {trade.indicators.adx !== undefined && (
                      <Box sx={{ p: 1.5, bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff', borderRadius: 1 }}>
                        <Typography sx={{ fontSize: '11px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 0.5 }}>ADX</Typography>
                        <Box sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#999' }}>
                          <Box>ADX: {trade.indicators.adx?.toFixed(2)}</Box>
                          {trade.indicators.plusDi !== undefined && <Box sx={{ color: '#22c55e' }}>+DI: {trade.indicators.plusDi?.toFixed(2)}</Box>}
                          {trade.indicators.minusDi !== undefined && <Box sx={{ color: '#ef4444' }}>-DI: {trade.indicators.minusDi?.toFixed(2)}</Box>}
                        </Box>
                      </Box>
                    )}

                    {/* 일목균형표 */}
                    {(trade.indicators.ichimokuTenkan !== undefined || trade.indicators.ichimokuKijun !== undefined) && (
                      <Box sx={{ p: 1.5, bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff', borderRadius: 1 }}>
                        <Typography sx={{ fontSize: '11px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 0.5 }}>일목균형표</Typography>
                        <Box sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#999' }}>
                          {trade.indicators.ichimokuTenkan !== undefined && <Box>전환선: ₩{trade.indicators.ichimokuTenkan?.toLocaleString()}</Box>}
                          {trade.indicators.ichimokuKijun !== undefined && <Box>기준선: ₩{trade.indicators.ichimokuKijun?.toLocaleString()}</Box>}
                        </Box>
                      </Box>
                    )}
                  </Box>
                </Box>
              )}

              {/* 적용 전략 정보 */}
              {trade.strategyName && (
                <Box sx={{
                  mb: 2,
                  p: 2,
                  bgcolor: isDark ? 'rgba(30, 35, 50, 0.7)' : '#f5f5f5',
                  borderRadius: 1,
                  border: isDark ? '1px solid rgba(80, 100, 160, 0.2)' : 'none',
                }}>
                  <Typography sx={{ fontWeight: 600, mb: 1.5, fontSize: '13px', color: isDark ? '#a1a1aa' : '#666' }}>
                    🎯 적용 전략
                  </Typography>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Chip
                      label={trade.strategyName}
                      size="small"
                      sx={{
                        bgcolor: isDark ? 'rgba(59, 130, 246, 0.2)' : 'rgba(59, 130, 246, 0.1)',
                        color: '#3b82f6',
                        fontWeight: 600,
                      }}
                    />
                    {trade.trendStatus && (
                      <Chip
                        label={trade.trendStatus}
                        size="small"
                        sx={{
                          bgcolor: trade.trendStatus?.includes('정배열')
                            ? 'rgba(34, 197, 94, 0.2)'
                            : trade.trendStatus?.includes('역배열')
                              ? 'rgba(239, 68, 68, 0.2)'
                              : 'rgba(168, 162, 158, 0.2)',
                          color: trade.trendStatus?.includes('정배열')
                            ? '#22c55e'
                            : trade.trendStatus?.includes('역배열')
                              ? '#ef4444'
                              : '#a8a29e',
                          fontWeight: 500,
                          fontSize: '11px',
                        }}
                      />
                    )}
                  </Box>
                </Box>
              )}

              {/* 충족 조건 목록 */}
              {trade.matchedConditions && trade.matchedConditions.length > 0 && (
                <Box sx={{
                  p: 2,
                  bgcolor: isDark ? 'rgba(30, 35, 50, 0.7)' : '#f5f5f5',
                  borderRadius: 1,
                  border: isDark ? '1px solid rgba(80, 100, 160, 0.2)' : 'none',
                }}>
                  <Typography sx={{ fontWeight: 600, mb: 1.5, fontSize: '13px', color: isDark ? '#a1a1aa' : '#666' }}>
                    ✅ 충족 조건 ({trade.matchedConditions.filter(c => c.matched).length}/{trade.matchedConditions.length})
                  </Typography>
                  {trade.matchedConditions.map((cond, idx) => (
                    <Box key={idx} sx={{
                      mb: 1.5,
                      p: 1.5,
                      bgcolor: isDark ? 'rgba(20, 25, 40, 0.5)' : '#fff',
                      borderRadius: 1,
                      border: `1px solid ${cond.matched ? (isDark ? 'rgba(34, 197, 94, 0.3)' : 'rgba(34, 197, 94, 0.5)') : (isDark ? 'rgba(239, 68, 68, 0.3)' : 'rgba(239, 68, 68, 0.5)')}`,
                      opacity: cond.matched ? 1 : 0.7,
                    }}>
                      {/* 조건 헤더 */}
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
                        <Typography sx={{ fontSize: '14px' }}>
                          {cond.matched ? '✅' : '❌'}
                        </Typography>
                        <Box sx={{ flex: 1 }}>
                          <Typography sx={{ fontSize: '13px', fontWeight: 600, color: isDark ? '#e0e0e0' : '#333' }}>
                            {cond.indicatorName || cond.conditionType}
                          </Typography>
                          <Typography sx={{ fontSize: '11px', color: isDark ? '#a1a1aa' : '#666' }}>
                            {cond.description}
                          </Typography>
                        </Box>
                      </Box>

                      {/* 값 정보 */}
                      <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(100px, 1fr))', gap: 1, mb: 1 }}>
                        {cond.currentValue != null && (
                          <Box sx={{ p: 0.5, bgcolor: isDark ? 'rgba(30, 35, 50, 0.5)' : '#f5f5f5', borderRadius: 0.5 }}>
                            <Typography sx={{ fontSize: '9px', color: isDark ? '#71717a' : '#999' }}>현재값</Typography>
                            <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#e0e0e0' : '#333' }}>
                              {typeof cond.currentValue === 'number' ? cond.currentValue.toFixed(4) : cond.currentValue}
                            </Typography>
                          </Box>
                        )}
                        {cond.previousValue != null && (
                          <Box sx={{ p: 0.5, bgcolor: isDark ? 'rgba(30, 35, 50, 0.5)' : '#f5f5f5', borderRadius: 0.5 }}>
                            <Typography sx={{ fontSize: '9px', color: isDark ? '#71717a' : '#999' }}>이전값</Typography>
                            <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#e0e0e0' : '#333' }}>
                              {cond.previousValue.toFixed(4)}
                            </Typography>
                          </Box>
                        )}
                        {cond.targetValue != null && (
                          <Box sx={{ p: 0.5, bgcolor: isDark ? 'rgba(30, 35, 50, 0.5)' : '#f5f5f5', borderRadius: 0.5 }}>
                            <Typography sx={{ fontSize: '9px', color: isDark ? '#71717a' : '#999' }}>기준값</Typography>
                            <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#e0e0e0' : '#333' }}>
                              {cond.targetValue.toFixed(4)}
                            </Typography>
                          </Box>
                        )}
                        {cond.compareValue != null && (
                          <Box sx={{ p: 0.5, bgcolor: isDark ? 'rgba(30, 35, 50, 0.5)' : '#f5f5f5', borderRadius: 0.5 }}>
                            <Typography sx={{ fontSize: '9px', color: isDark ? '#71717a' : '#999' }}>비교값</Typography>
                            <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#e0e0e0' : '#333' }}>
                              {cond.compareValue.toFixed(4)}
                            </Typography>
                          </Box>
                        )}
                        {cond.secondaryValue != null && (
                          <Box sx={{ p: 0.5, bgcolor: isDark ? 'rgba(30, 35, 50, 0.5)' : '#f5f5f5', borderRadius: 0.5 }}>
                            <Typography sx={{ fontSize: '9px', color: isDark ? '#71717a' : '#999' }}>보조값</Typography>
                            <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#e0e0e0' : '#333' }}>
                              {cond.secondaryValue.toFixed(4)}
                            </Typography>
                          </Box>
                        )}
                      </Box>

                      {/* 상세 설명 */}
                      {cond.detailDescription && (
                        <Box sx={{
                          mt: 1,
                          p: 1,
                          bgcolor: isDark ? 'rgba(30, 35, 50, 0.8)' : '#f0f0f0',
                          borderRadius: 0.5,
                          borderLeft: `3px solid ${cond.matched ? '#22c55e' : '#ef4444'}`,
                        }}>
                          <Typography sx={{
                            fontSize: '11px',
                            color: isDark ? '#a1a1aa' : '#666',
                            whiteSpace: 'pre-wrap',
                            fontFamily: 'monospace',
                          }}>
                            {cond.detailDescription}
                          </Typography>
                        </Box>
                      )}
                    </Box>
                  ))}
                </Box>
              )}

              {/* 조건 정보가 없을 때 */}
              {(!trade.matchedConditions || trade.matchedConditions.length === 0) && !trade.strategyName && (
                <Box sx={{
                  p: 2,
                  textAlign: 'center',
                  bgcolor: isDark ? 'rgba(30, 35, 50, 0.7)' : '#f5f5f5',
                  borderRadius: 1,
                }}>
                  <Typography sx={{ fontSize: '13px', color: isDark ? '#71717a' : '#999' }}>
                    기본 전략으로 생성된 신호입니다.
                    <br />
                    상세 조건 정보는 전략관리에서 설정한 규칙을 사용할 때 표시됩니다.
                  </Typography>
                </Box>
              )}

              {/* 보조지표 차트 (알림/투자분석 공통: 시계열이 있으면 최대한 표시) */}
              {backtestResult?.indicatorData && backtestResult.indicatorData.length > 0 && (() => {
                // 거래 시점 찾기
                const tradeTimestamp = trade.timestamp;
                const tradeTimeKey = normalizeTimeKey(tradeTimestamp);
                let tradeIndex = (backtestResult.indicatorData as any[]).findIndex((ind) => {
                  const indKey = normalizeTimeKey(ind.time);
                  return indKey !== '' && indKey === tradeTimeKey;
                });

                // 알림 상세는 전후 시계열만 내려오는 경우가 있어 정확히 매칭 실패할 수 있음.
                // 이때는 시계열 중앙을 거래 시점으로 간주하여 조건 차트를 표시한다.
                if (tradeIndex < 0) {
                  tradeIndex = Math.floor(((backtestResult.indicatorData as any[]).length - 1) / 2);
                }

                // 전후 5개 데이터 추출 (총 11개) - 더 집중된 뷰
                const startIdx = Math.max(0, tradeIndex - 5);
                const endIdx = Math.min((backtestResult.indicatorData as any[]).length, tradeIndex + 6);
                const chartRange = (backtestResult.indicatorData as any[]).slice(startIdx, endIdx);

                // 조건에서 사용된 지표 타입 추출
                const usedIndicators = new Set<string>();
                (trade.matchedConditions ?? []).forEach(cond => {
                  const type = cond.conditionType?.toUpperCase();
                  const indicatorName = cond.indicatorName?.toUpperCase();
                  const hint = `${type || ''} ${indicatorName || ''}`;
                  if (hint.includes('MACD') || hint.includes('HISTOGRAM')) usedIndicators.add('MACD');
                  if (hint.includes('RSI')) usedIndicators.add('RSI');
                  if (hint.includes('STOCHASTIC') || hint.includes('STOCH')) usedIndicators.add('STOCHASTIC');
                  if (hint.includes('CCI')) usedIndicators.add('CCI');
                  if (hint.includes('ADX') || hint.includes('DI') || hint.includes('DMI')) usedIndicators.add('ADX');
                  if (hint.includes('TRIX')) usedIndicators.add('TRIX');
                });

                // 알림 상세는 조건 메타가 비어있을 수 있어, 데이터 존재 기반으로 보조지표 차트를 보강한다.
                if (usedIndicators.size === 0) {
                  const has = (key: string) => chartRange.some((d: any) => d[key] != null);
                  if (has('stochK') || has('stochD')) usedIndicators.add('STOCHASTIC');
                  if (has('macdLine') || has('signalLine') || has('histogram')) usedIndicators.add('MACD');
                  if (has('rsi')) usedIndicators.add('RSI');
                  if (has('cci')) usedIndicators.add('CCI');
                  if (has('adx') || has('plusDI') || has('minusDI')) usedIndicators.add('ADX');
                  if (has('trix') || has('trixSignal')) usedIndicators.add('TRIX');
                }

                if (usedIndicators.size === 0) return null;

                // 차트 데이터 포맷
                const formattedData = chartRange.map((ind, idx) => {
                  const date = ind.time?.includes('T')
                    ? ind.time.split('T')[1]?.substring(0, 5) || ind.time.split('T')[0]?.substring(5)
                    : ind.time?.substring(5) || '';
                  return {
                    date,
                    fullTime: ind.time,
                    isTradePoint: startIdx + idx === tradeIndex,
                    // MACD
                    macdLine: ind.macdLine,
                    signalLine: ind.signalLine,
                    histogram: ind.histogram,
                    // RSI
                    rsi: ind.rsi,
                    // Stochastic
                    stochK: ind.stochK || ind.stochasticK,
                    stochD: ind.stochD || ind.stochasticD,
                    // CCI
                    cci: ind.cci || ind.cci13,
                    // ADX
                    adx: ind.adx,
                    plusDI: ind.plusDI || ind.plusDi,
                    minusDI: ind.minusDI || ind.minusDi,
                    // TRIX
                    trix: ind.trix,
                    trixSignal: ind.trixSignal,
                  };
                });

                const tradePointIndex = tradeIndex - startIdx;

                // 정사각형 차트 박스 스타일 - 팝업 전체 너비 활용
                const chartBoxStyle = {
                  width: '100%',
                  height: 350,
                  bgcolor: isDark ? 'rgba(20, 25, 40, 0.8)' : '#fff',
                  borderRadius: 2,
                  p: 2,
                  border: isDark ? '1px solid rgba(80, 100, 160, 0.3)' : '1px solid #e0e0e0',
                  boxShadow: isDark ? '0 4px 12px rgba(0,0,0,0.3)' : '0 2px 8px rgba(0,0,0,0.1)',
                };

                // 마커 크기
                const markerSize = 6;

                return (
                  <Box sx={{
                    mt: 2,
                    p: 2,
                    bgcolor: isDark ? 'rgba(30, 35, 50, 0.7)' : '#f5f5f5',
                    borderRadius: 1,
                    border: isDark ? '1px solid rgba(80, 100, 160, 0.2)' : 'none',
                  }}>
                    <Typography sx={{ fontWeight: 600, mb: 1.5, fontSize: '13px', color: isDark ? '#a1a1aa' : '#666' }}>
                      📊 조건 관련 지표 차트 (거래 시점 집중)
                    </Typography>

                    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, alignItems: 'center' }}>
                      {/* MACD 차트 */}
                      {usedIndicators.has('MACD') && (
                        <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: '100%' }}>
                          <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 1 }}>MACD</Typography>
                          <Box sx={chartBoxStyle}>
                            <ResponsiveContainer width="100%" height="100%">
                              <ComposedChart data={formattedData} margin={{ top: 15, right: 15, bottom: 25, left: 15 }}>
                                <CartesianGrid stroke={isDark ? '#27272a' : '#e0e0e0'} strokeDasharray="3 3" />
                                <XAxis dataKey="date" tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} interval={0} angle={-45} textAnchor="end" height={35} />
                                <YAxis tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} width={45} />
                                <ReferenceLine y={0} stroke={isDark ? '#52525b' : '#ccc'} strokeDasharray="2 2" />
                                <Bar dataKey="histogram" barSize={18}>
                                  {formattedData.map((entry, index) => (
                                    <Cell key={`cell-${index}`} fill={(entry.histogram ?? 0) >= 0 ? '#22c55e' : '#ef4444'} />
                                  ))}
                                </Bar>
                                <Line type="monotone" dataKey="macdLine" stroke="#2196F3" strokeWidth={2} dot={{ r: 3 }} />
                                <Line type="monotone" dataKey="signalLine" stroke="#FF9800" strokeWidth={2} dot={{ r: 3 }} />
                                <ReferenceLine x={formattedData[tradePointIndex]?.date} stroke={trade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'} strokeWidth={2} />
                                {formattedData[tradePointIndex]?.macdLine != null && (
                                  <ReferenceDot
                                    x={formattedData[tradePointIndex]?.date}
                                    y={formattedData[tradePointIndex]?.macdLine}
                                    r={markerSize}
                                    fill={trade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'}
                                    stroke="#fff"
                                    strokeWidth={1.5}
                                  />
                                )}
                              </ComposedChart>
                            </ResponsiveContainer>
                          </Box>
                        </Box>
                      )}

                      {/* RSI 차트 */}
                      {usedIndicators.has('RSI') && (
                        <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: '100%' }}>
                          <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 1 }}>RSI</Typography>
                          <Box sx={chartBoxStyle}>
                            <ResponsiveContainer width="100%" height="100%">
                              <LineChart data={formattedData} margin={{ top: 15, right: 15, bottom: 25, left: 15 }}>
                                <CartesianGrid stroke={isDark ? '#27272a' : '#e0e0e0'} strokeDasharray="3 3" />
                                <XAxis dataKey="date" tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} interval={0} angle={-45} textAnchor="end" height={35} />
                                <YAxis domain={[0, 100]} tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} width={35} ticks={[30, 50, 70]} />
                                <ReferenceLine y={70} stroke="#ef4444" strokeDasharray="3 3" strokeWidth={1.5} />
                                <ReferenceLine y={30} stroke="#22c55e" strokeDasharray="3 3" strokeWidth={1.5} />
                                <Line type="monotone" dataKey="rsi" stroke="#00BCD4" strokeWidth={2.5} dot={{ r: 4, fill: '#00BCD4' }} />
                                <ReferenceLine x={formattedData[tradePointIndex]?.date} stroke={trade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'} strokeWidth={2} />
                                {formattedData[tradePointIndex]?.rsi != null && (
                                  <ReferenceDot
                                    x={formattedData[tradePointIndex]?.date}
                                    y={formattedData[tradePointIndex]?.rsi}
                                    r={markerSize}
                                    fill={trade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'}
                                    stroke="#fff"
                                    strokeWidth={1.5}
                                  />
                                )}
                              </LineChart>
                            </ResponsiveContainer>
                          </Box>
                        </Box>
                      )}

                      {/* Stochastic 차트 */}
                      {usedIndicators.has('STOCHASTIC') && (
                        <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: '100%' }}>
                          <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 1 }}>Stochastic</Typography>
                          <Box sx={chartBoxStyle}>
                            <ResponsiveContainer width="100%" height="100%">
                              <LineChart data={formattedData} margin={{ top: 15, right: 15, bottom: 25, left: 15 }}>
                                <CartesianGrid stroke={isDark ? '#27272a' : '#e0e0e0'} strokeDasharray="3 3" />
                                <XAxis dataKey="date" tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} interval={0} angle={-45} textAnchor="end" height={35} />
                                <YAxis domain={[0, 100]} tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} width={35} ticks={[20, 50, 80]} />
                                <ReferenceLine y={80} stroke="#ef4444" strokeDasharray="3 3" strokeWidth={1.5} />
                                <ReferenceLine y={20} stroke="#22c55e" strokeDasharray="3 3" strokeWidth={1.5} />
                                <Line type="monotone" dataKey="stochK" stroke="#FF9500" strokeWidth={2.5} dot={{ r: 4, fill: '#FF9500' }} name="%K" />
                                <Line type="monotone" dataKey="stochD" stroke="#2196F3" strokeWidth={2} dot={{ r: 3, fill: '#2196F3' }} name="%D" />
                                <ReferenceLine x={formattedData[tradePointIndex]?.date} stroke={trade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'} strokeWidth={2} />
                                {formattedData[tradePointIndex]?.stochK != null && (
                                  <ReferenceDot
                                    x={formattedData[tradePointIndex]?.date}
                                    y={formattedData[tradePointIndex]?.stochK}
                                    r={markerSize}
                                    fill={trade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'}
                                    stroke="#fff"
                                    strokeWidth={1.5}
                                  />
                                )}
                              </LineChart>
                            </ResponsiveContainer>
                          </Box>
                        </Box>
                      )}

                      {/* CCI 차트 */}
                      {usedIndicators.has('CCI') && (
                        <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: '100%' }}>
                          <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 1 }}>CCI</Typography>
                          <Box sx={chartBoxStyle}>
                            <ResponsiveContainer width="100%" height="100%">
                              <LineChart data={formattedData} margin={{ top: 15, right: 15, bottom: 25, left: 15 }}>
                                <CartesianGrid stroke={isDark ? '#27272a' : '#e0e0e0'} strokeDasharray="3 3" />
                                <XAxis dataKey="date" tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} interval={0} angle={-45} textAnchor="end" height={35} />
                                <YAxis tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} width={45} />
                                <ReferenceLine y={100} stroke="#ef4444" strokeDasharray="3 3" strokeWidth={1.5} />
                                <ReferenceLine y={-100} stroke="#22c55e" strokeDasharray="3 3" strokeWidth={1.5} />
                                <ReferenceLine y={0} stroke={isDark ? '#52525b' : '#ccc'} strokeDasharray="2 2" />
                                <Line type="monotone" dataKey="cci" stroke="#9C27B0" strokeWidth={2.5} dot={{ r: 4, fill: '#9C27B0' }} />
                                <ReferenceLine x={formattedData[tradePointIndex]?.date} stroke={trade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'} strokeWidth={2} />
                                {formattedData[tradePointIndex]?.cci != null && (
                                  <ReferenceDot
                                    x={formattedData[tradePointIndex]?.date}
                                    y={formattedData[tradePointIndex]?.cci}
                                    r={markerSize}
                                    fill={trade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'}
                                    stroke="#fff"
                                    strokeWidth={1.5}
                                  />
                                )}
                              </LineChart>
                            </ResponsiveContainer>
                          </Box>
                        </Box>
                      )}

                      {/* ADX 차트 */}
                      {usedIndicators.has('ADX') && (
                        <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: '100%' }}>
                          <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 1 }}>ADX / DI</Typography>
                          <Box sx={chartBoxStyle}>
                            <ResponsiveContainer width="100%" height="100%">
                              <LineChart data={formattedData} margin={{ top: 15, right: 15, bottom: 25, left: 15 }}>
                                <CartesianGrid stroke={isDark ? '#27272a' : '#e0e0e0'} strokeDasharray="3 3" />
                                <XAxis dataKey="date" tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} interval={0} angle={-45} textAnchor="end" height={35} />
                                <YAxis domain={[0, 'auto']} tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} width={35} />
                                <Line type="monotone" dataKey="adx" stroke="#FFD700" strokeWidth={2.5} dot={{ r: 4, fill: '#FFD700' }} name="ADX" />
                                <Line type="monotone" dataKey="plusDI" stroke="#22c55e" strokeWidth={2} dot={{ r: 3 }} name="+DI" />
                                <Line type="monotone" dataKey="minusDI" stroke="#ef4444" strokeWidth={2} dot={{ r: 3 }} name="-DI" />
                                <ReferenceLine x={formattedData[tradePointIndex]?.date} stroke={trade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'} strokeWidth={2} />
                                {formattedData[tradePointIndex]?.adx != null && (
                                  <ReferenceDot
                                    x={formattedData[tradePointIndex]?.date}
                                    y={formattedData[tradePointIndex]?.adx}
                                    r={markerSize}
                                    fill={trade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'}
                                    stroke="#fff"
                                    strokeWidth={1.5}
                                  />
                                )}
                              </LineChart>
                            </ResponsiveContainer>
                          </Box>
                        </Box>
                      )}

                      {/* TRIX 차트 */}
                      {usedIndicators.has('TRIX') && (
                        <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: '100%' }}>
                          <Typography sx={{ fontSize: '12px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', mb: 1 }}>TRIX</Typography>
                          <Box sx={chartBoxStyle}>
                            <ResponsiveContainer width="100%" height="100%">
                              <LineChart data={formattedData} margin={{ top: 15, right: 15, bottom: 25, left: 15 }}>
                                <CartesianGrid stroke={isDark ? '#27272a' : '#e0e0e0'} strokeDasharray="3 3" />
                                <XAxis dataKey="date" tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} interval={0} angle={-45} textAnchor="end" height={35} />
                                <YAxis tick={{ fontSize: 10, fill: isDark ? '#71717a' : '#888' }} width={45} />
                                <ReferenceLine y={0} stroke={isDark ? '#52525b' : '#ccc'} strokeDasharray="2 2" />
                                <Line type="monotone" dataKey="trix" stroke="#E91E63" strokeWidth={2.5} dot={{ r: 4, fill: '#E91E63' }} name="TRIX" />
                                <Line type="monotone" dataKey="trixSignal" stroke="#9C27B0" strokeWidth={2} dot={{ r: 3, fill: '#9C27B0' }} name="Signal" />
                                <ReferenceLine x={formattedData[tradePointIndex]?.date} stroke={trade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'} strokeWidth={2} />
                                {formattedData[tradePointIndex]?.trix != null && (
                                  <ReferenceDot
                                    x={formattedData[tradePointIndex]?.date}
                                    y={formattedData[tradePointIndex]?.trix}
                                    r={markerSize}
                                    fill={trade.tradeType === 'BUY' ? '#22c55e' : '#ef4444'}
                                    stroke="#fff"
                                    strokeWidth={1.5}
                                  />
                                )}
                              </LineChart>
                            </ResponsiveContainer>
                          </Box>
                        </Box>
                      )}
                    </Box>

                    <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 2, mt: 1.5 }}>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                        <Box sx={{ width: 10, height: 10, borderRadius: '50%', bgcolor: trade.tradeType === 'BUY' ? '#22c55e' : '#ef4444', border: '1.5px solid #fff' }} />
                        <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>
                          {trade.tradeType === 'BUY' ? '매수' : '매도'} 시점
                        </Typography>
                      </Box>
                      <Typography sx={{ fontSize: '10px', color: isDark ? '#52525b' : '#999' }}>
                        | 차트 범위: 전후 5개 캔들
                      </Typography>
                    </Box>
                  </Box>
                );
              })()}
            </Box>
          )}
        </DialogContent>
      </Dialog>
  );
}

/** 투자분석 매수/매도 신호 상세 — 페이지 내부에 정의하면 매 렌더마다 타입이 바뀌어 Dialog가 깜빡임 */
export const TradeSignalDetailDialog = memo(TradeSignalDetailDialogInner);
