'use client';

import { useEffect, useRef, useCallback, useState } from 'react';
import {
  createChart,
  ColorType,
  CandlestickSeries,
  HistogramSeries,
  type IChartApi,
  type ISeriesApi,
  type CandlestickData,
  type MouseEventParams,
} from 'lightweight-charts';

// ============================================================================
// INTERFACES & TYPES (Interface Segregation Principle)
// ============================================================================

interface CandlestickWithVolume extends CandlestickData {
  volume?: number;
}

interface VolumeData {
  time: string | number;
  value: number;
  color: string;
}

interface ChartTheme {
  background: string;
  textColor: string;
  gridColor: string;
  borderColor: string;
}

interface StockChartProps {
  symbol?: string;
  interval?: string;
  count?: number;
  onCandleClick?: (clickedCandle: CandlestickData, historical60: CandlestickData[], symbol: string, interval: string, count: number) => void;
  onDataLoaded?: (data: CandlestickData[]) => void;
  width?: number;
  height?: number;
  theme?: 'dark' | 'light';
}

interface PredictionResult {
  action_code: number;
  action_label: string;
  clicked_date: string;
  close_price: number;
  symbol: string;
  confidence?: number;
  predicted_price?: number;
  horizon_days?: number;
  forecasted_prices?: {
    day: number;
    date: string;
    predicted_price: number;
    change_percent: number;
  }[];
}

interface ChartState {
  isLoading: boolean;
  isLoadingMore: boolean;
  selectedCandle: number | null;
  chartData: CandlestickData[];
  earliestDate: Date | null;
  predictionResult: PredictionResult | null;
  isPredicting: boolean;
}

// ============================================================================
// DATA ACCESS LAYER (Single Responsibility Principle)
// ============================================================================

class StockDataService {
  private static instance: StockDataService;

  static getInstance(): StockDataService {
    if (!StockDataService.instance) {
      StockDataService.instance = new StockDataService();
    }
    return StockDataService.instance;
  }

  async fetchStockData(
    symbol: string,
    interval: string,
    count: number,
    endDate?: Date
  ): Promise<{ candleData: CandlestickData[]; volumeData: VolumeData[] }> {
    try {
      const endParam = endDate ? `&end=${endDate.toISOString()}` : '';
      const url = `/api/candles?symbol=${symbol}&interval=${interval}&count=${count}${endParam}`;


      const response = await fetch(url);

      if (!response.ok) {
        throw new Error(`API Error: ${response.status} ${response.statusText}`);
      }

      const candleData: CandlestickData[] = await response.json();

      if (!Array.isArray(candleData) || candleData.length === 0) {
        throw new Error('Invalid data format received from API');
      }

      const formattedCandleData = this.formatCandleData(candleData);
      const volumeData = this.generateVolumeData(formattedCandleData);

      return { candleData: formattedCandleData, volumeData };

    } catch (error) {
      console.error('Error fetching stock data:', error);
      console.log('Falling back to generated data...');
      return this.generateFallbackData(count);
    }
  }

  private formatCandleData(candleData: CandlestickData[]): CandlestickData[] {
    return candleData.map(candle => ({
      ...candle,
      time: typeof candle.time === 'number' ? candle.time : candle.time
    }));
  }

  private generateVolumeData(candleData: CandlestickData[]): VolumeData[] {
    return candleData.map(candle => ({
      time: candle.time,
      value: Math.round(Math.random() * 50000000 + 10000000),
      color: candle.close > candle.open ? '#26a69a40' : '#ef535040'
    }));
  }

  generateFallbackData(count: number): { candleData: CandlestickData[]; volumeData: VolumeData[] } {
    console.log('Generating fallback data...');
    const candleData: CandlestickData[] = [];
    const volumeData: VolumeData[] = [];
    let basePrice = 9675;

    for (let i = 0; i < count; i++) {
      const date = new Date('2024-01-01');
      date.setDate(date.getDate() + i);
      const timeString = date.toISOString().split('T')[0];

      const change = (Math.random() - 0.5) * basePrice * 0.02;
      const open = Math.round(basePrice);
      const close = Math.round(basePrice + change);
      const high = Math.round(Math.max(open, close) + Math.random() * 100);
      const low = Math.round(Math.min(open, close) - Math.random() * 100);
      const volume = Math.round(Math.random() * 50000000 + 10000000);

      candleData.push({ time: timeString, open, high, low, close });
      volumeData.push({
        time: timeString,
        value: volume,
        color: close > open ? '#26a69a40' : '#ef535040'
      });

      basePrice = close;
    }

    return { candleData, volumeData };
  }

  getEarliestDate(candleData: CandlestickData[]): Date | null {
    if (candleData.length === 0) return null;

    const firstCandle = candleData[0];
    return typeof firstCandle.time === 'number'
      ? new Date(firstCandle.time * 1000)
      : new Date(firstCandle.time);
  }
}

// ============================================================================
// CHART CONFIGURATION (Single Responsibility Principle)
// ============================================================================

class ChartConfigurationService {
  private themes: Record<'dark' | 'light', ChartTheme> = {
    dark: {
      background: '#0f1419',
      textColor: '#d1d4dc',
      gridColor: '#2a2e39',
      borderColor: '#4a5568'
    },
    light: {
      background: '#ffffff',
      textColor: '#333333',
      gridColor: '#e1e3e6',
      borderColor: '#e1e3e6'
    }
  };

  getChartOptions(theme: 'dark' | 'light', width: number, height: number) {
    const themeConfig = this.themes[theme];

    return {
      layout: {
        background: { type: ColorType.Solid, color: themeConfig.background },
        textColor: themeConfig.textColor,
      },
      width,
      height,
      grid: {
        vertLines: { color: themeConfig.gridColor },
        horzLines: { color: themeConfig.gridColor },
      },
      timeScale: {
        timeVisible: true,
        borderColor: themeConfig.borderColor,
      },
      rightPriceScale: {
        borderColor: themeConfig.borderColor,
        scaleMargins: { top: 0.1, bottom: 0.2 },
      },
    };
  }

  getCandlestickSeriesOptions() {
    return {
      upColor: '#26a69a',
      downColor: '#ef5350',
      borderVisible: false,
      wickUpColor: '#26a69a',
      wickDownColor: '#ef5350',
    };
  }

  getVolumeSeriesOptions() {
    return {
      color: '#26a69a',
      priceFormat: { type: 'volume' as const },
      priceScaleId: 'volume',
    };
  }
}

// ============================================================================
// CHART INTERACTION HANDLER (Single Responsibility Principle)
// ============================================================================

class ChartInteractionHandler {
  constructor(
    private onCandleClick?: (clickedCandle: CandlestickData, historical60: CandlestickData[], symbol: string, interval: string, count: number) => void
  ) { }

  handleCandleClick = async (
    param: MouseEventParams,
    chartData: CandlestickData[],
    setSelectedCandle: (index: number | null) => void,
    setPredictionResult: (result: PredictionResult | null) => void,
    setIsPredicting: (isPredicting: boolean) => void,
    symbol: string = 'BBCA.JK',
    interval: string = '1d',
    count: number = 60
  ) => {
    const clickedTime = param.time;
    const clickedIndex = chartData.findIndex(candle => candle.time === clickedTime);

    if (clickedIndex === -1) return;

    setSelectedCandle(clickedIndex);
    setIsPredicting(true);
    setPredictionResult(null);

    const clickedCandle = chartData[clickedIndex];
    const clickedCandleDate = typeof clickedCandle.time === 'number' 
      ? new Date(clickedCandle.time * 1000)
      : new Date(clickedCandle.time);

    try {
      const url = `/api/predict`;
      const response = await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          symbol,
          clicked_date: clickedCandleDate.toISOString().split('T')[0]
        })
      });

      if (!response.ok) {
        throw new Error(`API Error: ${response.status}`);
      }

      const data: PredictionResult = await response.json();
      setPredictionResult(data);
      console.log('Prediction result:', data);
    } catch (error) {
      console.error('Error fetching prediction:', error);
      // Show error state or fallback
      setPredictionResult({
        action_code: -1,
        action_label: 'ERROR',
        clicked_date: clickedCandleDate.toISOString().split('T')[0],
        close_price: clickedCandle.close,
        symbol,
        horizon_days: 6,
        forecasted_prices: []
      });
    } finally {
      setIsPredicting(false);
    }
  };
}

// ============================================================================
// INFINITE SCROLL HANDLER (Single Responsibility Principle)
// ============================================================================

class InfiniteScrollHandler {
  constructor(
    private dataService: StockDataService,
    private symbol: string,
    private interval: string,
    private count: number
  ) { }

  async loadMoreHistoricalData(
    earliestDate: Date | null,
    chartData: CandlestickData[],
    candlestickSeries: ISeriesApi<'Candlestick'>,
    volumeSeries: ISeriesApi<'Histogram'>,
    setChartData: (data: CandlestickData[]) => void,
    setEarliestDate: (date: Date | null) => void
  ): Promise<void> {
    if (!earliestDate) return;


    try {
      const endDate = new Date(earliestDate.getTime() - 24 * 60 * 60 * 1000);
      const { candleData, volumeData } = await this.dataService.fetchStockData(
        this.symbol,
        this.interval,
        this.count,
        endDate
      );

      if (candleData.length > 0) {
        const mergedCandleData = [...candleData, ...chartData];
        const mergedVolumeData = [...volumeData, ...this.generateExistingVolumeData(chartData)];

        candlestickSeries.setData(mergedCandleData);
        volumeSeries.setData(mergedVolumeData);

        setChartData(mergedCandleData);

        const newEarliestDate = this.dataService.getEarliestDate(candleData);
        setEarliestDate(newEarliestDate);

        console.log('Loaded', candleData.length, 'more historical candles');
      }
    } catch (error) {
      console.error('Error loading more data:', error);
    }
  }

  private generateExistingVolumeData(chartData: CandlestickData[]): VolumeData[] {
    return chartData.map(candle => ({
      time: candle.time,
      value: Math.round(Math.random() * 50000000 + 10000000),
      color: candle.close > candle.open ? '#26a69a40' : '#ef535040'
    }));
  }

  handleVisibleLogicalRangeChange = (
    logicalRange: any,
    isLoadingMore: boolean,
    loadMoreCallback: () => Promise<void>
  ) => {
    if (!logicalRange || isLoadingMore) return;

    if (logicalRange.from <= 5) {
      console.log('User scrolled to beginning, loading more data...');
      loadMoreCallback();
    }
  };
}

// ============================================================================
// PRICE CALCULATOR (Single Responsibility Principle)
// ============================================================================

class PriceCalculatorService {
  calculatePriceMetrics(chartData: CandlestickData[]) {
    const currentPrice = chartData.length > 0 ? chartData[chartData.length - 1].close : 0;
    const priceChange = chartData.length > 1 ?
      chartData[chartData.length - 1].close - chartData[chartData.length - 2].close : 0;
    const percentChange = chartData.length > 1 ?
      (priceChange / chartData[chartData.length - 2].close) * 100 : 0;

    return { currentPrice, priceChange, percentChange };
  }
}

// ============================================================================
// MAIN COMPONENT (Open/Closed Principle - Open for extension, Closed for modification)
// ============================================================================

export default function BBCAStockChart({
  symbol = 'BBCA.JK',
  interval = '1d',
  count = 100,
  onCandleClick,
  onDataLoaded,
  width,
  height = 500,
  theme = 'light'
}: StockChartProps) {
  // Services (Dependency Injection)
  const dataService = StockDataService.getInstance();
  const configService = new ChartConfigurationService();
  const interactionHandler = new ChartInteractionHandler(onCandleClick);
  const scrollHandler = new InfiniteScrollHandler(dataService, symbol, interval, count);
  const priceCalculator = new PriceCalculatorService();

  // Refs
  const chartContainerRef = useRef<HTMLDivElement>(null);
  const chartRef = useRef<IChartApi | null>(null);
  const candlestickSeriesRef = useRef<ISeriesApi<'Candlestick'> | null>(null);
  const volumeSeriesRef = useRef<ISeriesApi<'Histogram'> | null>(null);

  // State
  const [state, setState] = useState<ChartState>({
    isLoading: true,
    isLoadingMore: false,
    selectedCandle: null,
    chartData: [],
    earliestDate: null,
    predictionResult: null,
    isPredicting: false,
  });

  // State updaters
  const setIsLoading = (isLoading: boolean) =>
    setState(prev => ({ ...prev, isLoading }));

  const setIsLoadingMore = (isLoadingMore: boolean) =>
    setState(prev => ({ ...prev, isLoadingMore }));

  const setSelectedCandle = (selectedCandle: number | null) =>
    setState(prev => ({ ...prev, selectedCandle }));

  const setChartData = (chartData: CandlestickData[]) =>
    setState(prev => ({ ...prev, chartData }));

  const setEarliestDate = (earliestDate: Date | null) =>
    setState(prev => ({ ...prev, earliestDate }));

  const setPredictionResult = (predictionResult: PredictionResult | null) =>
    setState(prev => ({ ...prev, predictionResult }));

  const setIsPredicting = (isPredicting: boolean) =>
    setState(prev => ({ ...prev, isPredicting }));

  // Load more data handler
  const loadMoreHistoricalData = useCallback(async () => {
    if (!candlestickSeriesRef.current || !volumeSeriesRef.current || state.isLoadingMore) return;

    setIsLoadingMore(true);

    await scrollHandler.loadMoreHistoricalData(
      state.earliestDate,
      state.chartData,
      candlestickSeriesRef.current,
      volumeSeriesRef.current,
      setChartData,
      setEarliestDate
    );

    setIsLoadingMore(false);
  }, [state.earliestDate, state.chartData, state.isLoadingMore, scrollHandler]);

  // Handle candle click with current state
  const handleCandleClick = useCallback((param: MouseEventParams) => {
    interactionHandler.handleCandleClick(
      param, 
      state.chartData, 
      setSelectedCandle, 
      setPredictionResult, 
      setIsPredicting, 
      symbol, 
      interval, 
      count
    );
  }, [state.chartData, interactionHandler, symbol, interval, count]);

  // Handle scroll with current state
  const handleVisibleLogicalRangeChange = useCallback((logicalRange: any) => {
    scrollHandler.handleVisibleLogicalRangeChange(
      logicalRange,
      state.isLoadingMore,
      loadMoreHistoricalData
    );
  }, [state.isLoadingMore, loadMoreHistoricalData, scrollHandler]);

  // Chart initialization
  useEffect(() => {
    if (!chartContainerRef.current) return;

    console.log('Initializing chart...');
    setIsLoading(true);

    const chartWidth = width || chartContainerRef.current.clientWidth;
    const chartOptions = configService.getChartOptions(theme, chartWidth, height);
    const chart = createChart(chartContainerRef.current, chartOptions);

    const candlestickSeries = chart.addSeries(CandlestickSeries, configService.getCandlestickSeriesOptions());
    const volumeSeries = chart.addSeries(HistogramSeries, configService.getVolumeSeriesOptions());

    chartRef.current = chart;
    candlestickSeriesRef.current = candlestickSeries;
    volumeSeriesRef.current = volumeSeries;

    // Load initial data
    const loadInitialData = async () => {
      try {
        const { candleData, volumeData } = await dataService.fetchStockData(symbol, interval, count);

        candlestickSeries.setData(candleData);
        volumeSeries.setData(volumeData);

        setChartData(candleData);
        setEarliestDate(dataService.getEarliestDate(candleData));

        onDataLoaded?.(candleData);

        setTimeout(() => {
          chart.timeScale().fitContent();
          setIsLoading(false);
        }, 100);

      } catch (error) {
        console.error('Error loading initial data:', error);
        setIsLoading(false);
      }
    };

    // Handle resize
    const handleResize = () => {
      if (chartContainerRef.current) {
        chart.applyOptions({ width: chartContainerRef.current.clientWidth });
      }
    };

    window.addEventListener('resize', handleResize);
    loadInitialData();

    // Cleanup
    return () => {
      console.log('Cleaning up chart');
      chart.remove();
      window.removeEventListener('resize', handleResize);
    };
  }, [symbol, interval, count, theme, height, width]);

  // Subscribe to events with current handlers (separate effect)
  useEffect(() => {
    if (!chartRef.current) return;

    const chart = chartRef.current;

    // Subscribe to click events
    chart.subscribeClick(handleCandleClick);

    // Subscribe to visible logical range changes
    chart.timeScale().subscribeVisibleLogicalRangeChange(handleVisibleLogicalRangeChange);

    // Cleanup subscriptions
    return () => {
      chart.unsubscribeClick(handleCandleClick);
      chart.timeScale().unsubscribeVisibleLogicalRangeChange(handleVisibleLogicalRangeChange);
    };
  }, [handleCandleClick, handleVisibleLogicalRangeChange]);

  // Calculate price metrics
  const { currentPrice, priceChange, percentChange } = priceCalculator.calculatePriceMetrics(state.chartData);

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      {/* Header */}
      <div className="mb-6 bg-white rounded-lg shadow-sm p-6">
        <div className="flex items-center justify-between mb-4">
          <h1 className="text-3xl font-bold text-gray-900">BBCA Trading Analysis</h1>
          <div className="flex items-center space-x-2">
            <div className="w-3 h-3 bg-green-500 rounded-full animate-pulse"></div>
            <span className="text-sm text-gray-600">Live Data</span>
          </div>
        </div>
        
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          {/* Current Price */}
          <div className="bg-gradient-to-r from-blue-50 to-indigo-50 p-4 rounded-lg">
            <p className="text-sm text-gray-600 mb-1">Current Price</p>
            <p className="text-2xl font-bold text-gray-900">
              Rp {currentPrice.toLocaleString('id-ID', { maximumFractionDigits: 0 })}
            </p>
          </div>
          
          {/* Price Change */}
          <div className={`p-4 rounded-lg ${priceChange >= 0 ? 'bg-gradient-to-r from-green-50 to-emerald-50' : 'bg-gradient-to-r from-red-50 to-pink-50'}`}>
            <p className="text-sm text-gray-600 mb-1">24h Change</p>
            <div className="flex items-center space-x-2">
              <span className={`text-2xl ${priceChange >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                {priceChange >= 0 ? '↗' : '↘'}
              </span>
              <span className={`text-xl font-bold ${priceChange >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                {priceChange >= 0 ? '+' : ''}{percentChange.toFixed(2)}%
              </span>
            </div>
          </div>
          
          {/* Data Points */}
          <div className="bg-gradient-to-r from-purple-50 to-violet-50 p-4 rounded-lg">
            <p className="text-sm text-gray-600 mb-1">Data Points</p>
            <p className="text-2xl font-bold text-gray-900">{state.chartData.length}</p>
          </div>
        </div>
        
        {/* Instructions */}
        <div className="mt-4 bg-blue-50 border border-blue-200 rounded-lg p-4">
          <div className="flex items-center space-x-3">
            <div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
              <span className="text-blue-600 font-bold">💡</span>
            </div>
            <div>
              <p className="text-sm font-medium text-blue-900">
                Interactive Analysis
              </p>
              <p className="text-xs text-blue-700">
                Click any candle to get AI-powered PatchTST analysis and trading recommendations
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Chart Container */}
      <div className="bg-white rounded-lg shadow-sm p-6 mb-6">
        <div className="relative">
          <div
            ref={chartContainerRef}
            className="w-full border border-gray-200 rounded-lg bg-white"
            style={{ height: height }}
          />

          {/* Loading overlay */}
          {state.isLoading && (
            <div className="absolute inset-0 flex items-center justify-center bg-white bg-opacity-90 rounded-lg">
              <div className="text-center">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
                <p className="text-lg font-medium text-gray-700">Loading {symbol}</p>
                <p className="text-sm text-gray-500">Fetching market data...</p>
              </div>
            </div>
          )}

          {/* Loading more indicator */}
          {state.isLoadingMore && (
            <div className="absolute top-4 left-4 bg-blue-600 text-white px-4 py-2 rounded-lg shadow-lg">
              <div className="flex items-center space-x-2">
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                <span className="text-sm font-medium">Loading historical data...</span>
              </div>
            </div>
          )}

          {/* Chart Info */}
          <div className="absolute bottom-4 right-4 bg-gray-900 bg-opacity-80 text-white px-4 py-2 rounded-lg">
            <p className="text-sm font-medium">{symbol}</p>
            <p className="text-xs opacity-75">{state.chartData.length} candles</p>
          </div>
        </div>
      </div>

      {/* Prediction Result Card */}
      {(state.predictionResult || state.isPredicting) && (
        <div className="fixed top-4 right-4 bg-white border border-gray-200 rounded-xl shadow-xl p-6 w-[28rem] max-h-[80vh] overflow-y-auto z-50">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-semibold text-gray-800">
              {state.isPredicting ? 'Analyzing...' : 'AI Prediction'}
            </h3>
            <button 
              onClick={() => {
                setPredictionResult(null);
                setIsPredicting(false);
                setSelectedCandle(null);
              }}
              className="text-gray-400 hover:text-gray-600 transition-colors"
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>

          {state.isPredicting ? (
            <div className="text-center py-8">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
              <p className="text-gray-600 font-medium">Running PatchTST analysis...</p>
              <p className="text-sm text-gray-500 mt-2">Generating 6-day forecast...</p>
            </div>
          ) : state.predictionResult && (
            <div>
              {/* Action Badge */}
              <div className={`inline-flex items-center px-4 py-3 rounded-lg border-2 mb-4 ${
                state.predictionResult.action_code === 0 ? 'bg-red-50 border-red-200 text-red-800' :
                state.predictionResult.action_code === 1 ? 'bg-green-50 border-green-200 text-green-800' :
                'bg-blue-50 border-blue-200 text-blue-800'
              }`}>
                <span className="text-2xl mr-3">
                  {state.predictionResult.action_code === 0 ? '📉' : 
                   state.predictionResult.action_code === 1 ? '📈' : '⚖️'}
                </span>
                <div>
                  <span className="font-bold text-xl block">{state.predictionResult.action_label}</span>
                  {state.predictionResult.horizon_days && (
                    <span className="text-sm opacity-75">{state.predictionResult.horizon_days}-day horizon</span>
                  )}
                </div>
              </div>

              {/* Stock Info */}
              <div className="bg-gray-50 rounded-lg p-4 mb-4">
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <p className="text-xs text-gray-500 uppercase tracking-wide">Symbol</p>
                    <p className="font-mono font-semibold text-gray-800">{state.predictionResult.symbol}</p>
                  </div>
                  <div>
                    <p className="text-xs text-gray-500 uppercase tracking-wide">Date</p>
                    <p className="font-mono font-semibold text-gray-800">{state.predictionResult.clicked_date}</p>
                  </div>
                </div>
                <div className="mt-3 pt-3 border-t border-gray-200">
                  <p className="text-xs text-gray-500 uppercase tracking-wide">Current Price</p>
                  <p className="font-mono font-bold text-lg text-gray-800">
                    Rp {state.predictionResult.close_price.toLocaleString('id-ID', { maximumFractionDigits: 2 })}
                  </p>
                </div>
              </div>

              {/* 6-Day Forecast */}
              {state.predictionResult.forecasted_prices && state.predictionResult.forecasted_prices.length > 0 && (
                <div className="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-lg p-4 mb-4">
                  <h4 className="font-semibold text-gray-800 mb-3 flex items-center">
                    <span className="text-blue-600 mr-2">📊</span>
                    6-Day Price Forecast
                  </h4>
                  <div className="space-y-2">
                    {state.predictionResult.forecasted_prices.map((forecast, index) => (
                      <div key={index} className="flex justify-between items-center bg-white rounded-lg p-3 shadow-sm">
                        <div className="flex items-center space-x-3">
                          <div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
                            <span className="text-blue-600 font-semibold text-sm">D{forecast.day}</span>
                          </div>
                          <div>
                            <p className="font-mono text-sm text-gray-600">{forecast.date}</p>
                          </div>
                        </div>
                        <div className="text-right">
                          <p className="font-mono font-semibold text-gray-800">
                            Rp {forecast.predicted_price.toLocaleString('id-ID', { maximumFractionDigits: 0 })}
                          </p>
                          <p className={`text-sm font-medium ${
                            forecast.change_percent >= 0 ? 'text-green-600' : 'text-red-600'
                          }`}>
                            {forecast.change_percent >= 0 ? '+' : ''}{forecast.change_percent.toFixed(2)}%
                          </p>
                        </div>
                      </div>
                    ))}
                  </div>
                  
                  {/* Summary */}
                  <div className="mt-4 pt-3 border-t border-blue-200">
                    <div className="grid grid-cols-2 gap-3 text-sm">
                      <div>
                        <p className="text-gray-600">Avg Change</p>
                        <p className={`font-semibold ${
                          state.predictionResult.forecasted_prices.reduce((sum, f) => sum + f.change_percent, 0) / state.predictionResult.forecasted_prices.length >= 0
                            ? 'text-green-600' 
                            : 'text-red-600'
                        }`}>
                          {((state.predictionResult.forecasted_prices.reduce((sum, f) => sum + f.change_percent, 0) / state.predictionResult.forecasted_prices.length)).toFixed(2)}%
                        </p>
                      </div>
                      <div>
                        <p className="text-gray-600">Expected by Day 6</p>
                        <p className="font-semibold text-gray-800">
                          Rp {state.predictionResult.forecasted_prices[state.predictionResult.forecasted_prices.length - 1]?.predicted_price.toLocaleString('id-ID', { maximumFractionDigits: 0 })}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {/* Description */}
              <div className="bg-blue-50 rounded-lg p-4 mb-4">
                <p className="text-sm text-blue-800 leading-relaxed">
                  {state.predictionResult.action_code === 0 ? 
                    'Our PatchTST AI model suggests selling this stock based on technical patterns and forecasts a potential decline over the next 6 days.' :
                    state.predictionResult.action_code === 1 ?
                    'Our PatchTST AI model suggests buying this stock based on technical patterns and forecasts potential growth over the next 6 days.' :
                    'Our PatchTST AI model suggests holding this stock based on technical patterns and forecasts mixed signals over the next 6 days.'
                  }
                </p>
              </div>

              {/* Confidence & Accuracy */}
              {state.predictionResult.confidence && (
                <div className="bg-green-50 rounded-lg p-4 mb-4">
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium text-green-800">Model Confidence</span>
                    <span className="text-lg font-bold text-green-800">{(state.predictionResult.confidence * 100).toFixed(1)}%</span>
                  </div>
                  <div className="w-full bg-green-200 rounded-full h-2 mt-2">
                    <div 
                      className="bg-green-600 h-2 rounded-full transition-all duration-300"
                      style={{ width: `${(state.predictionResult.confidence || 0) * 100}%` }}
                    ></div>
                  </div>
                </div>
              )}

              {/* Disclaimer */}
              <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-3">
                <p className="text-xs text-yellow-800">
                  ⚠️ This is an AI-generated prediction using PatchTST for educational purposes only. 
                  Market conditions can change rapidly. Always do your own research and consider consulting with financial advisors before making investment decisions.
                </p>
              </div>
            </div>
          )}
        </div>
      )}

      {/* Selected Candle Info */}
      {state.selectedCandle !== null && (
        <div className="fixed bottom-4 left-4 bg-white border border-gray-200 rounded-lg shadow-lg p-4 w-64">
          <h4 className="font-semibold text-gray-800 mb-2">Selected Candle</h4>
          <div className="text-sm text-gray-600">
            <p>Position: #{state.selectedCandle + 1}</p>
            <p>Date: {String(state.chartData[state.selectedCandle]?.time)}</p>
            <p>Close: Rp {state.chartData[state.selectedCandle]?.close.toLocaleString('id-ID')}</p>
          </div>
        </div>
      )}
    </div>
  );
}