import React, { createContext, useContext, useState, useCallback } from 'react';

interface IndicatorPopupContextType {
  isPopupOpen: boolean;
  openPopup: () => void;
  closePopup: () => void;
  chartData: any[];
  setChartData: (data: any[]) => void;
  chartMargin: { top: number; right: number; bottom: number; left: number };
  setChartMargin: (margin: { top: number; right: number; bottom: number; left: number }) => void;
  // 크로스헤어 동기화용
  hoveredDate: string | null;
  setHoveredDate: (date: string | null) => void;
  hoveredIndex: number | null;
  setHoveredIndex: (index: number | null) => void;
  // 활성화된 보조지표 타입 (마우스가 위치한 보조지표)
  activeIndicatorType: 'macd' | 'stochastic' | 'rsi' | 'volume' | null;
  setActiveIndicatorType: (type: 'macd' | 'stochastic' | 'rsi' | 'volume' | null) => void;
}

const IndicatorPopupContext = createContext<IndicatorPopupContextType | undefined>(undefined);

export const IndicatorPopupProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [isPopupOpen, setIsPopupOpen] = useState(false);
  const [chartData, setChartData] = useState<any[]>([]);
  const [chartMargin, setChartMargin] = useState({ top: 5, right: 55, bottom: 20, left: 55 });
  // 크로스헤어 동기화용 상태
  const [hoveredDate, setHoveredDate] = useState<string | null>(null);
  const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);
  // 활성화된 보조지표 타입
  const [activeIndicatorType, setActiveIndicatorType] = useState<'macd' | 'stochastic' | 'rsi' | 'volume' | null>(null);
  
  const openPopup = useCallback(() => {
    setIsPopupOpen(true);
  }, []);
  
  const closePopup = useCallback(() => {
    setIsPopupOpen(false);
  }, []);
  
  return (
    <IndicatorPopupContext.Provider
      value={{
        isPopupOpen,
        openPopup,
        closePopup,
        chartData,
        setChartData,
        chartMargin,
        setChartMargin,
        hoveredDate,
        setHoveredDate,
        hoveredIndex,
        setHoveredIndex,
        activeIndicatorType,
        setActiveIndicatorType,
      }}
    >
      {children}
    </IndicatorPopupContext.Provider>
  );
};

export const useIndicatorPopup = () => {
  const context = useContext(IndicatorPopupContext);
  if (!context) {
    throw new Error('useIndicatorPopup must be used within IndicatorPopupProvider');
  }
  return context;
};

