import React, { createContext, useContext, useState, useEffect, useCallback, useRef } from 'react';
import upbitApiService, { UpbitMarket } from '../services/upbitApi';
import { MacdResult, StockRequest } from '../types/stock';
import { useIndicatorVisibility } from './IndicatorVisibilityContext';
import { useIndicatorSettings } from './IndicatorSettingsContext';

interface Statistics {
  totalDays: number;
  buySignals: number;
  sellSignals: number;
  currentPrice: number;
  priceChange: number;
  priceChangePercent: number;
  currentSignal: string;
}

interface ChartCache {
  [key: number]: { data: MacdResult[]; timestamp: string };
}

interface UpbitDataContextType {
  // 데이터 상태
  macdData: MacdResult[];
  loading: boolean;
  error: string | null;
  currentCrypto: string;
  backendSettings: any | null;  // ✅ 백엔드에서 실제 사용한 설정값
  hasInitialData: boolean;
  isDataLoading: boolean;
  isLoadingMore: boolean;
  statistics: Statistics | null;
  
  // 설정 상태
  symbol: string;
  timeInterval: string;
  
  // 커서 네비게이션
  cursor: number;
  chartCache: ChartCache;
  hasPastData: boolean;
  
  // 추세 강도
  trendStrength: number;
  
  // 메서드
  setSymbol: (symbol: string) => void;
  setTimeInterval: (interval: string) => void;
  fetchChartData: (targetSymbol?: string, targetInterval?: string) => Promise<void>;
  handleScrollLoadMore: (direction: 'past' | 'future', referenceDate: string, dataCount?: number) => Promise<void>;
  refreshData: () => void;
  
  // 프리로드 상태
  isPreloaded: boolean;
}

const UpbitDataContext = createContext<UpbitDataContextType | undefined>(undefined);

export const useUpbitData = () => {
  const context = useContext(UpbitDataContext);
  if (!context) {
    throw new Error('useUpbitData must be used within a UpbitDataProvider');
  }
  return context;
};

interface UpbitDataProviderProps {
  children: React.ReactNode;
}

export const UpbitDataProvider: React.FC<UpbitDataProviderProps> = ({ children }) => {
  // 볼린저 밴드 설정 (IndicatorVisibilityContext에서)
  const { settings: visibilitySettings } = useIndicatorVisibility();
  // ✅ 보조지표 설정 변경 감지 (IndicatorSettingsContext에서)
  const { settingsVersion, indicatorSettings: contextIndicatorSettings, getLatestSettings } = useIndicatorSettings();
  
  const [macdData, setMacdData] = useState<MacdResult[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [currentCrypto, setCurrentCrypto] = useState<string>('');
  const [backendSettings, setBackendSettings] = useState<any | null>(null);  // ✅ 백엔드 설정값 상태
  
  // 점진적 로딩 상태
  const [isDataLoading, setIsDataLoading] = useState(false);
  const [hasInitialData, setHasInitialData] = useState(false);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  
  // 커서 기반 네비게이션 상태
  const [cursor, setCursor] = useState<number>(0);
  const [chartCache, setChartCache] = useState<ChartCache>({});
  const [hasPastData, setHasPastData] = useState<boolean>(true);
  
  // 폼 상태
  const [symbol, setSymbol] = useState<string>('KRW-BTC');
  const [timeInterval, setTimeInterval] = useState<string>('1d');
  
  // 추세 강도
  const [trendStrength, setTrendStrength] = useState<number>(0);
  
  // 프리로드 상태
  const [isPreloaded, setIsPreloaded] = useState(false);
  
  // 이전 값 추적
  const prevSymbolRef = useRef(symbol);
  const prevIntervalRef = useRef(timeInterval);
  const latestRequestIdRef = useRef(0);
  const latestRequestKeyRef = useRef<string>('');

  // 통계 정보 계산
  const getStatistics = useCallback((): Statistics | null => {
    if (macdData.length === 0) return null;

    const buySignals = macdData.filter(d => d.signal === 'BUY').length;
    const sellSignals = macdData.filter(d => d.signal === 'SELL').length;
    
    const latestData = macdData[macdData.length - 1];
    const firstData = macdData[0];
    const priceChange = latestData.close - firstData.close;
    const priceChangePercent = (priceChange / firstData.close) * 100;

    return {
      totalDays: macdData.length,
      buySignals,
      sellSignals,
      currentPrice: latestData.close,
      priceChange,
      priceChangePercent,
      currentSignal: latestData.signal,
    };
  }, [macdData]);

  // interval을 분 단위로 변환
  const getIntervalMinutes = (interval: string): number => {
    switch (interval) {
      case '1m': return 1;
      case '3m': return 3;
      case '5m': return 5;
      case '10m': return 10;
      case '15m': return 15;
      case '30m': return 30;
      case '1h': return 60;
      case '4h': return 240;
      case '1d': return 1440;
      case '1w': return 10080;
      case '1M': return 43200;
      default: return 1440;
    }
  };

  // 데이터 조회 함수
  const fetchChartData = useCallback(async (targetSymbol?: string, targetInterval?: string) => {
    const sym = targetSymbol || symbol;
    const interval = targetInterval || timeInterval;
    const requestId = ++latestRequestIdRef.current;
    const requestKey = `${sym}|${interval}`;
    latestRequestKeyRef.current = requestKey;
    
    if (!sym || !upbitApiService.validateCryptoSymbol(sym)) {
      return;
    }

    setIsDataLoading(true);
    setLoading(true);
    setError(null);
    setCurrentCrypto(sym);

    try {
      // ✅ 보조지표 설정 로드 (Context에서 직접 가져오기 - 실시간 반영)
      const indicatorSettings = contextIndicatorSettings;
      
      console.log('🔍 [UpbitDataContext] VR/VR2 설정 (독립적인 보조지표):', {
        vrPeriod: indicatorSettings.vrPeriod,
        vr2Enabled: indicatorSettings.vr2Enabled,  // ✅ vr2Enabled 추가
        vr2Period: indicatorSettings.vr2Period
      });
      
      // ✅ Context의 getLatestSettings()로 최신 설정값 동기적으로 읽기 (DB 기반)
      const latestSettings = getLatestSettings();
      const vr2Enabled = latestSettings.vr2Enabled || false;
      
      const request: StockRequest = {
        symbol: sym.toUpperCase(),
        interval: interval,
        count: 1000,
        // ✅ 모든 보조지표 파라미터 전송 (DEFAULT_INDICATOR_SETTINGS와 일치)
        // MACD
        fastPeriod: indicatorSettings.macdFastPeriod || 12,
        slowPeriod: indicatorSettings.macdSlowPeriod || 26,
        signalPeriod: indicatorSettings.macdSignalPeriod || 9,
        // Stochastic
        stochasticKPeriod: indicatorSettings.stochasticKPeriod || 12,
        stochasticDPeriod: indicatorSettings.stochasticDPeriod || 5,
        stochasticSlowing: indicatorSettings.stochasticSlowing || 5,
        // RSI
        rsiPeriod: indicatorSettings.rsiPeriod || 9,
        // CCI
        cciPeriod: indicatorSettings.cciPeriod || 13,
        cciSignalPeriod: indicatorSettings.cciSignalPeriod || 10,
        // Williams %R
        williamsRPeriod: indicatorSettings.williamsRPeriod || 11,
        // ADX/DMI (업비트 방식: 기간 하나만 사용, adxSmoothing은 dmiPeriod와 동일)
        adxPeriod: indicatorSettings.adxPeriod || 11,
        dmiPeriod: indicatorSettings.dmiPeriod || 14,
        adxSmoothing: indicatorSettings.dmiPeriod || 14,  // DMI 기간과 동일하게 전달
        // BWI
        bwiPeriod: indicatorSettings.bwiPeriod || 20,
        // OBV
        obvPeriod: indicatorSettings.obvPeriod || 9,
        obvSignalPeriod: indicatorSettings.obvSignalPeriod || 9,
        // TRIX
        trixPeriod: indicatorSettings.trixPeriod || 12,
        trixSignalPeriod: indicatorSettings.trixSignalPeriod || 9,
        // Volume OSC
        volumeOscShortPeriod: indicatorSettings.volumeOscShortPeriod || 10,
        volumeOscLongPeriod: indicatorSettings.volumeOscLongPeriod || 20,
        // VR
        vrPeriod: indicatorSettings.vrPeriod || 10,
        // VR2 (조건부 보조지표) - localStorage에서 읽은 최신 값 사용
        vr2Enabled: vr2Enabled,
        vr2Period: indicatorSettings.vr2Period || 10,
        // Psychological
        newPsychologicalPeriod: indicatorSettings.newPsychologicalPeriod || 5,
        investPsychologicalPeriod: indicatorSettings.investPsychologicalPeriod || 10,
        // Disparity
        disparityUltraShortPeriod: indicatorSettings.disparityUltraShortPeriod || 5,
        disparityShortPeriod: indicatorSettings.disparityShortPeriod || 10,
        disparityMidPeriod: indicatorSettings.disparityMidPeriod || 20,
        disparityLongPeriod: indicatorSettings.disparityLongPeriod || 60,
        // Bollinger Bands
        bollingerPeriod: visibilitySettings.bollingerPeriod || 20,
        bollingerStdDev: visibilitySettings.bollingerStdDev || 2.0,
      };

      console.log('📡 [API 요청] 볼린저밴드 설정:', {
        bollingerPeriod: request.bollingerPeriod,
        bollingerStdDev: request.bollingerStdDev
      });
      
      console.log('📡 [API 요청] VR/VR2 설정 (DB 기반 최신값):', {
        vrPeriod: request.vrPeriod,
        vr2Enabled: request.vr2Enabled,  // ✅ DB 기반 최신 값
        vr2Period: request.vr2Period
      });
      
      console.log('📡 [API 요청] OBV 설정:', {
        obvPeriod: request.obvPeriod,
        obvSignalPeriod: request.obvSignalPeriod,
        contextValue: indicatorSettings.obvSignalPeriod
      });

      const result = await upbitApiService.analyzeCryptoMacd(request);
      if (requestKey !== latestRequestKeyRef.current) {
        console.log(`[UpbitDataContext] stale response ignored: symbol=${sym}, interval=${interval}, requestId=${requestId}, key=${requestKey}, latest=${latestRequestKeyRef.current}`);
        return;
      }
      
      if (result.data && result.data.length > 0) {
        setMacdData(result.data);
        setBackendSettings(result.backendSettings);  // ✅ 백엔드 설정값 저장
        setHasInitialData(true);
        setIsPreloaded(true);
        
        // 커서 초기화 및 캐시 저장
        setCursor(0);
        const firstItem = result.data[0];
        const cacheKey = firstItem.timestamp || firstItem.date;
        setChartCache({ 0: { data: result.data, timestamp: cacheKey } });
        setHasPastData(true);
        
        console.log(`📌 데이터 로드 완료: ${result.data.length}개, symbol=${sym}, interval=${interval}`);
        
        // ✅ Stochastic Slow 값 로그 (최근 5개)
        console.log('📊 [Stochastic Slow Debug] 최근 5개 데이터:');
        const debugData = result.data.slice(-5);
        debugData.forEach((item, idx) => {
          console.log(`  [${result.data.length - 5 + idx}] ${item.date || item.timestamp}:`, 
            `%K=${item.stochasticK?.toFixed(2) || 'N/A'}, %D=${item.stochasticD?.toFixed(2) || 'N/A'}`);
        });
        
        // 추세 강도 조회
        try {
          const trendData = await upbitApiService.getTrendStrength('default');
          const marketTrend = trendData.find(t => t.symbol === sym);
          if (marketTrend) {
            setTrendStrength(marketTrend.trendStrength);
          } else {
            setTrendStrength(0);
          }
        } catch (trendErr) {
          console.warn('추세 강도 조회 실패:', trendErr);
          setTrendStrength(0);
        }
      } else {
        setError('데이터를 찾을 수 없습니다.');
      }
    } catch (err: any) {
      console.error('❌ 데이터 로드 오류:', err);
      setError(err.message || '데이터 로드 실패');
    } finally {
      setLoading(false);
      setIsDataLoading(false);
    }
  }, [symbol, timeInterval, visibilitySettings.bollingerPeriod, visibilitySettings.bollingerStdDev, contextIndicatorSettings, settingsVersion]);

  // 스크롤 로드 핸들러
  const handleScrollLoadMore = useCallback(async (direction: 'past' | 'future', referenceDate: string, dataCount?: number) => {
    if (isLoadingMore || !symbol) return;
    
    const newCursor = direction === 'past' ? cursor - 1 : cursor + 1;
    
    if (newCursor > 0) {
      console.log('⚠️ 현재 시점(cursor=0)을 넘어선 미래 데이터는 없습니다');
      return;
    }
    
    // ✅ 기간 변경 시작 - 캐시 여부와 관계없이 로딩 상태 먼저 설정
    setIsLoadingMore(true);
    
    if (chartCache[newCursor]) {
      console.log(`📦 캐시에서 데이터 로드: cursor=${newCursor}`, chartCache[newCursor].data.length, '개');
      // 캐시된 데이터로 즉시 업데이트 (약간의 딜레이로 로딩 상태 표시)
      setTimeout(() => {
        setMacdData(chartCache[newCursor].data);
        setCursor(newCursor);
        setIsLoadingMore(false);
      }, 150);
      return;
    }
    
    try {
      const dayjs = (await import('dayjs')).default;
      const refDate = dayjs(referenceDate);
      
      if (!refDate.isValid()) {
        console.error('❌ 유효하지 않은 날짜:', referenceDate);
        setIsLoadingMore(false);
        return;
      }
      
      const isIntraday = timeInterval.endsWith('m') || timeInterval.endsWith('h');
      let endDate: string;
      
      if (direction === 'past') {
        if (isIntraday) {
          const intervalMinutes = getIntervalMinutes(timeInterval);
          endDate = refDate.subtract(intervalMinutes, 'minute').format('YYYY-MM-DDTHH:mm:ss');
        } else if (timeInterval === '1w') {
          endDate = refDate.subtract(1, 'week').format('YYYY-MM-DD');
        } else if (timeInterval === '1M') {
          endDate = refDate.subtract(1, 'month').format('YYYY-MM-DD');
        } else {
          endDate = refDate.subtract(1, 'day').format('YYYY-MM-DD');
        }
      } else {
        if (newCursor === 0) {
          // ✅ 보조지표 설정 로드 (Context에서 직접 가져오기)
          const indicatorSettings = contextIndicatorSettings;
          
          const request: StockRequest = {
            symbol: symbol.toUpperCase(),
            interval: timeInterval,
            count: 1000,
            // MACD
            fastPeriod: indicatorSettings.macdFastPeriod || 12,
            slowPeriod: indicatorSettings.macdSlowPeriod || 26,
            signalPeriod: indicatorSettings.macdSignalPeriod || 9,
            // Stochastic
            stochasticKPeriod: indicatorSettings.stochasticKPeriod || 12,
            stochasticDPeriod: indicatorSettings.stochasticDPeriod || 5,
            stochasticSlowing: indicatorSettings.stochasticSlowing || 5,
            // RSI
            rsiPeriod: indicatorSettings.rsiPeriod || 9,
            // CCI
            cciPeriod: indicatorSettings.cciPeriod || 13,
            cciSignalPeriod: indicatorSettings.cciSignalPeriod || 10,
            // Williams %R
            williamsRPeriod: indicatorSettings.williamsRPeriod || 11,
            // ADX/DMI
            adxPeriod: indicatorSettings.adxPeriod || 11,
            dmiPeriod: indicatorSettings.dmiPeriod || 14,
            adxSmoothing: indicatorSettings.adxSmoothing || 14,
            // BWI
            bwiPeriod: indicatorSettings.bwiPeriod || 20,
            // OBV
            obvPeriod: indicatorSettings.obvPeriod || 9,
            obvSignalPeriod: indicatorSettings.obvSignalPeriod || 9,
            // TRIX
            trixPeriod: indicatorSettings.trixPeriod || 12,
            trixSignalPeriod: indicatorSettings.trixSignalPeriod || 9,
            // Volume OSC
            volumeOscShortPeriod: indicatorSettings.volumeOscShortPeriod || 10,
            volumeOscLongPeriod: indicatorSettings.volumeOscLongPeriod || 20,
            // VR
            vrPeriod: indicatorSettings.vrPeriod || 10,
            // VR2 (독립적인 보조지표, 항상 계산됨)
            vr2Period: indicatorSettings.vr2Period || 10,
            // Psychological
            newPsychologicalPeriod: indicatorSettings.newPsychologicalPeriod || 5,
            investPsychologicalPeriod: indicatorSettings.investPsychologicalPeriod || 10,
            // Disparity
            disparityUltraShortPeriod: indicatorSettings.disparityUltraShortPeriod || 5,
            disparityShortPeriod: indicatorSettings.disparityShortPeriod || 10,
            disparityMidPeriod: indicatorSettings.disparityMidPeriod || 20,
            disparityLongPeriod: indicatorSettings.disparityLongPeriod || 60,
            // Bollinger Bands
            bollingerPeriod: visibilitySettings.bollingerPeriod || 20,
            bollingerStdDev: visibilitySettings.bollingerStdDev || 2.0,
          };
          
          console.log('📡 [실시간 업데이트 API 요청] OBV 설정:', {
            obvPeriod: request.obvPeriod,
            obvSignalPeriod: request.obvSignalPeriod,
            contextValue: indicatorSettings.obvSignalPeriod
          });
          
          const result = await upbitApiService.analyzeCryptoMacd(request);
          
          if (result.data && result.data.length > 0) {
            setMacdData(result.data);
            setBackendSettings(result.backendSettings);  // ✅ 백엔드 설정값 저장
            setCursor(0);
            const firstItem = result.data[0];
            setChartCache(prev => ({
              ...prev,
              0: { data: result.data, timestamp: firstItem.timestamp || firstItem.date }
            }));
          }
          setIsLoadingMore(false);
          return;
        }
        
        const lastItem = macdData[macdData.length - 1];
        const lastDate = dayjs(lastItem.timestamp || lastItem.date);
        
        if (isIntraday) {
          const intervalMinutes = getIntervalMinutes(timeInterval);
          endDate = lastDate.add(200 * intervalMinutes, 'minute').format('YYYY-MM-DDTHH:mm:ss');
        } else if (timeInterval === '1w') {
          endDate = lastDate.add(200, 'week').format('YYYY-MM-DD');
        } else if (timeInterval === '1M') {
          endDate = lastDate.add(200, 'month').format('YYYY-MM-DD');
        } else {
          endDate = lastDate.add(200, 'day').format('YYYY-MM-DD');
        }
      }
      
      // ✅ 보조지표 설정 로드 (Context에서 직접 가져오기)
      const indicatorSettings = contextIndicatorSettings;
      
      // ✅ VR2 설정 디버깅
      console.log('🔍 [VR2 Context 확인]', {
        vr2Enabled: indicatorSettings.vr2Enabled,
        vr2Period: indicatorSettings.vr2Period,
        fullSettings: indicatorSettings
      });
      
      const request: StockRequest = {
        symbol: symbol.toUpperCase(),
        interval: timeInterval,
        count: 1000,
        ...(isIntraday ? { endDateTime: endDate } : { endDate }),
        // MACD
        fastPeriod: indicatorSettings.macdFastPeriod || 12,
        slowPeriod: indicatorSettings.macdSlowPeriod || 26,
        signalPeriod: indicatorSettings.macdSignalPeriod || 9,
        // Stochastic
        stochasticKPeriod: indicatorSettings.stochasticKPeriod || 12,
        stochasticDPeriod: indicatorSettings.stochasticDPeriod || 5,
        stochasticSlowing: indicatorSettings.stochasticSlowing || 5,
        // RSI
        rsiPeriod: indicatorSettings.rsiPeriod || 9,
        // CCI
        cciPeriod: indicatorSettings.cciPeriod || 13,
        cciSignalPeriod: indicatorSettings.cciSignalPeriod || 10,
        // Williams %R
        williamsRPeriod: indicatorSettings.williamsRPeriod || 11,
        // ADX/DMI (업비트 방식: 기간 하나만 사용, adxSmoothing은 dmiPeriod와 동일)
        adxPeriod: indicatorSettings.adxPeriod || 11,
        dmiPeriod: indicatorSettings.dmiPeriod || 14,
        adxSmoothing: indicatorSettings.dmiPeriod || 14,  // DMI 기간과 동일하게 전달
        // BWI
        bwiPeriod: indicatorSettings.bwiPeriod || 20,
        // OBV
        obvPeriod: indicatorSettings.obvPeriod || 9,
        obvSignalPeriod: indicatorSettings.obvSignalPeriod || 9,
        // TRIX
        trixPeriod: indicatorSettings.trixPeriod || 12,
        trixSignalPeriod: indicatorSettings.trixSignalPeriod || 9,
        // Volume OSC
        volumeOscShortPeriod: indicatorSettings.volumeOscShortPeriod || 10,
        volumeOscLongPeriod: indicatorSettings.volumeOscLongPeriod || 20,
        // VR
        vrPeriod: indicatorSettings.vrPeriod || 10,
        // VR2 (조건부 보조지표)
        vr2Enabled: indicatorSettings.vr2Enabled || false,
        vr2Period: indicatorSettings.vr2Period || 10,
        // Psychological
        newPsychologicalPeriod: indicatorSettings.newPsychologicalPeriod || 5,
        investPsychologicalPeriod: indicatorSettings.investPsychologicalPeriod || 10,
        // Disparity
        disparityUltraShortPeriod: indicatorSettings.disparityUltraShortPeriod || 5,
        disparityShortPeriod: indicatorSettings.disparityShortPeriod || 10,
        disparityMidPeriod: indicatorSettings.disparityMidPeriod || 20,
        disparityLongPeriod: indicatorSettings.disparityLongPeriod || 60,
        // Bollinger Bands
        bollingerPeriod: visibilitySettings.bollingerPeriod || 20,
        bollingerStdDev: visibilitySettings.bollingerStdDev || 2.0,
      };
      
      console.log('📡 [데이터 재로드 API 요청] OBV 설정:', {
        obvPeriod: request.obvPeriod,
        obvSignalPeriod: request.obvSignalPeriod,
        contextValue: indicatorSettings.obvSignalPeriod
      });
      
      const result = await upbitApiService.analyzeCryptoMacd(request);
      
      if (result.data && result.data.length > 0) {
        setMacdData(result.data);
        setBackendSettings(result.backendSettings);  // ✅ 백엔드 설정값 저장
        setCursor(newCursor);
        
        const firstItem = result.data[0];
        setChartCache(prev => ({
          ...prev,
          [newCursor]: { data: result.data, timestamp: firstItem.timestamp || firstItem.date }
        }));
        
        if (direction === 'past') {
          setHasPastData(true);
        }
      } else {
        if (direction === 'past') {
          setHasPastData(false);
        }
      }
    } catch (err: any) {
      console.error('❌ 추가 데이터 로드 오류:', err);
    } finally {
      setIsLoadingMore(false);
    }
  }, [isLoadingMore, symbol, cursor, chartCache, timeInterval, macdData, visibilitySettings.bollingerPeriod, visibilitySettings.bollingerStdDev, contextIndicatorSettings, settingsVersion]);

  // 데이터 새로고침
  const refreshData = useCallback(() => {
    if (symbol && upbitApiService.validateCryptoSymbol(symbol)) {
      fetchChartData(symbol, timeInterval);
    }
  }, [symbol, timeInterval, fetchChartData]);

  // 심볼 변경 핸들러
  const handleSetSymbol = useCallback((newSymbol: string) => {
    if (newSymbol !== symbol) {
      setSymbol(newSymbol);
      setChartCache({});
      setCursor(0);
      setHasPastData(true);
      fetchChartData(newSymbol, timeInterval);
    }
  }, [symbol, timeInterval, fetchChartData]);

  // 인터벌 변경 핸들러
  const handleSetTimeInterval = useCallback((newInterval: string) => {
    if (newInterval !== timeInterval) {
      setTimeInterval(newInterval);
      setChartCache({});
      setCursor(0);
      setHasPastData(true);
      fetchChartData(symbol, newInterval);
    }
  }, [symbol, timeInterval, fetchChartData]);

  // 앱 시작 프리로드는 선택 종목 요청과 경쟁하여 종목이 덮어씌워질 수 있어 비활성화

  // ✅ 보조지표 설정 변경 감지 및 자동 갱신 (settingsVersion 변경 시에만)
  const prevSettingsVersionRef = useRef(settingsVersion);
  useEffect(() => {
    console.log('🔍 [UpbitDataContext useEffect 트리거]', {
      prevVersion: prevSettingsVersionRef.current,
      currentVersion: settingsVersion,
      hasInitialData,
      symbol,
      timeInterval
    });
    
    // settingsVersion이 실제로 변경되었는지 확인 (다른 의존성 변경으로 인한 중복 호출 방지)
    if (prevSettingsVersionRef.current === settingsVersion) {
      console.log('⏭️ [설정 변경 감지] settingsVersion 변경 없음 - 스킵');
      return;
    }
    prevSettingsVersionRef.current = settingsVersion;
    
    // 첫 렌더링은 스킵 (초기 로드와 중복 방지)
    if (!hasInitialData) {
      console.log('⏭️ [설정 변경 감지] hasInitialData가 false - 스킵');
      return;
    }
    
    console.log('🔄 [설정 변경 감지] 보조지표 설정이 변경되어 차트 데이터 갱신 중...', { 
      settingsVersion,
      vrPeriod: contextIndicatorSettings.vrPeriod,
      vr2Enabled: contextIndicatorSettings.vr2Enabled,
      vr2Period: contextIndicatorSettings.vr2Period
    });
    
    // 설정 변경 시 현재 심볼과 인터벌로 데이터 재조회
    if (symbol && upbitApiService.validateCryptoSymbol(symbol)) {
      console.log('✅ [설정 변경 감지] fetchChartData 호출:', symbol, timeInterval);
      fetchChartData(symbol, timeInterval);
    } else {
      console.log('❌ [설정 변경 감지] symbol이 유효하지 않음:', symbol);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [settingsVersion, hasInitialData, symbol, timeInterval]);

  const statistics = getStatistics();

  return (
    <UpbitDataContext.Provider
      value={{
        macdData,
        loading,
        error,
        currentCrypto,
        backendSettings,  // ✅ 백엔드 설정값 제공
        hasInitialData,
        isDataLoading,
        isLoadingMore,
        statistics,
        symbol,
        timeInterval,
        cursor,
        chartCache,
        hasPastData,
        trendStrength,
        setSymbol: handleSetSymbol,
        setTimeInterval: handleSetTimeInterval,
        fetchChartData,
        handleScrollLoadMore,
        refreshData,
        isPreloaded,
      }}
    >
      {children}
    </UpbitDataContext.Provider>
  );
};

export default UpbitDataContext;

