// ===== Live Chart Page — Real-Time Candlestick Chart =====
// Two modes:
//   1. Index (SENSEX/NIFTY spot) — from UnderlyingPriceBuffer SQL (~30s ticks)
//   2. Option Strike (CE/PE)    — from Parquet snapshots in Azure Blob
// Auto-refreshes every 30s during market hours.

function LiveChartPage() {
  const [mode, setMode] = React.useState('SENSEX');          // SENSEX | NIFTY
  const [chartMode, setChartMode] = React.useState('index'); // index | option
  const [interval, setInterval_] = React.useState(5);
  const [candles, setCandles] = React.useState([]);
  const [latestPrice, setLatestPrice] = React.useState(null);
  const [prevClose, setPrevClose] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [lastUpdated, setLastUpdated] = React.useState(null);
  const [autoRefresh, setAutoRefresh] = React.useState(true);

  // Option-specific state
  const [symbols, setSymbols] = React.useState([]);
  const [selectedSymbol, setSelectedSymbol] = React.useState('');
  const [symbolSearch, setSymbolSearch] = React.useState('');
  const [loadingSymbols, setLoadingSymbols] = React.useState(false);

  const chartContainerRef = React.useRef(null);
  const chartRef = React.useRef(null);
  const candleSeriesRef = React.useRef(null);

  const intervals = [
    { value: 1, label: '1m' },
    { value: 3, label: '3m' },
    { value: 5, label: '5m' },
    { value: 15, label: '15m' },
  ];

  // Load option symbols when switching to option mode or changing index
  React.useEffect(() => {
    if (chartMode !== 'option') return;
    let cancelled = false;
    (async () => {
      setLoadingSymbols(true);
      try {
        const data = await API.get(`/api/live-chart/symbols?mode=${mode}`);
        if (!cancelled && data && data.symbols) {
          setSymbols(data.symbols);
          // Auto-select first ATM-ish symbol if none selected
          if (!selectedSymbol || !data.symbols.find(s => s.symbol === selectedSymbol)) {
            const first = data.symbols.length > 0 ? data.symbols[0].symbol : '';
            setSelectedSymbol(first);
          }
        }
      } catch (e) {
        if (!cancelled) setSymbols([]);
      } finally {
        if (!cancelled) setLoadingSymbols(false);
      }
    })();
    return () => { cancelled = true; };
  }, [chartMode, mode]);

  // Fetch candle data
  const fetchCandles = React.useCallback(async (showLoader) => {
    if (showLoader) setLoading(true);
    setError(null);
    try {
      let data;
      if (chartMode === 'index') {
        data = await API.get(`/api/live-chart/candles?root=${mode}&interval=${interval}&hours=7`);
      } else {
        if (!selectedSymbol) { setLoading(false); return; }
        data = await API.get(`/api/live-chart/option-candles?symbol=${encodeURIComponent(selectedSymbol)}&mode=${mode}&interval=${interval}`);
      }
      if (data && data.candles) {
        setCandles(data.candles);
        if (data.candles.length > 0) {
          const last = data.candles[data.candles.length - 1];
          setLatestPrice(last.close);
          if (data.candles.length > 1) {
            setPrevClose(data.candles[0].open);
          }
        } else {
          setLatestPrice(null);
          setPrevClose(null);
        }
        setLastUpdated(new Date());
      }
    } catch (e) {
      setError(e?.message || 'Failed to load chart data');
    } finally {
      setLoading(false);
    }
  }, [mode, chartMode, interval, selectedSymbol]);

  // Initial load + auto-refresh
  React.useEffect(() => {
    fetchCandles(true);
    if (!autoRefresh) return;
    const timer = window.setInterval(() => fetchCandles(false), 30000);
    return () => window.clearInterval(timer);
  }, [fetchCandles, autoRefresh]);

  // Cleanup chart on mode/interval/symbol change
  React.useEffect(() => {
    return () => {
      if (chartRef.current) {
        chartRef.current.remove();
        chartRef.current = null;
        candleSeriesRef.current = null;
      }
      if (chartContainerRef.current && chartContainerRef.current._ro) {
        chartContainerRef.current._ro.disconnect();
      }
    };
  }, [mode, chartMode, interval, selectedSymbol]);

  // Create / update chart
  React.useEffect(() => {
    if (!chartContainerRef.current || typeof LightweightCharts === 'undefined') return;
    if (candles.length === 0) return;

    const watermark = chartMode === 'index' ? mode : selectedSymbol;

    if (!chartRef.current) {
      const chart = LightweightCharts.createChart(chartContainerRef.current, {
        height: 520,
        layout: {
          background: { type: 'solid', color: '#131722' },
          textColor: '#d1d4dc',
          fontFamily: "'Segoe UI', system-ui, -apple-system, sans-serif",
          fontSize: 12,
        },
        grid: {
          vertLines: { color: '#1e222d', style: 0 },
          horzLines: { color: '#1e222d', style: 0 },
        },
        crosshair: {
          mode: LightweightCharts.CrosshairMode.Normal,
          vertLine: { color: '#758696', width: 1, style: LightweightCharts.LineStyle.Dashed, labelBackgroundColor: '#2962FF' },
          horzLine: { color: '#758696', width: 1, style: LightweightCharts.LineStyle.Dashed, labelBackgroundColor: '#2962FF' },
        },
        rightPriceScale: {
          borderColor: '#2B2B43',
          scaleMargins: { top: 0.02, bottom: 0.02 },
          autoScale: true,
        },
        timeScale: {
          borderColor: '#2B2B43',
          timeVisible: true,
          secondsVisible: false,
          fixLeftEdge: true,
          fixRightEdge: true,
          barSpacing: interval <= 3 ? 6 : 10,
        },
        handleScroll: { mouseWheel: true, pressedMouseMove: true, horzTouchDrag: true, vertTouchDrag: true },
        handleScale: { axisPressedMouseMove: true, mouseWheel: true, pinch: true },
        watermark: {
          visible: true, fontSize: 48, horzAlign: 'center', vertAlign: 'center',
          color: 'rgba(255, 255, 255, 0.04)', text: watermark,
        },
      });

      const candleSeries = chart.addCandlestickSeries({
        upColor: '#26a69a',
        downColor: '#ef5350',
        borderUpColor: '#26a69a',
        borderDownColor: '#ef5350',
        wickUpColor: '#26a69a',
        wickDownColor: '#ef5350',
        priceLineVisible: true,
        lastValueVisible: true,
        priceFormat: { type: 'price', precision: 2, minMove: 0.01 },
      });

      chartRef.current = chart;
      candleSeriesRef.current = candleSeries;

      const ro = new ResizeObserver(entries => {
        for (const entry of entries) chart.applyOptions({ width: entry.contentRect.width });
      });
      ro.observe(chartContainerRef.current);
      chartContainerRef.current._ro = ro;
    }

    if (candleSeriesRef.current) {
      candleSeriesRef.current.setData(candles.map(c => ({
        time: c.time,
        open: Number(c.open),
        high: Number(c.high),
        low: Number(c.low),
        close: Number(c.close),
      })));
    }

    if (chartRef.current) {
      chartRef.current.applyOptions({ watermark: { text: watermark } });
    }
  }, [candles, mode, chartMode, interval, selectedSymbol]);

  // Price change
  const priceChange = latestPrice && prevClose ? latestPrice - prevClose : null;
  const priceChangePct = priceChange && prevClose ? (priceChange / prevClose) * 100 : null;
  const isPositive = priceChange !== null ? priceChange >= 0 : null;

  // Symbol filter
  const filteredSymbols = symbolSearch
    ? symbols.filter(s => s.symbol.toLowerCase().includes(symbolSearch.toLowerCase()))
    : symbols;

  return React.createElement('div', { className: 'live-chart-page' },
    // Header
    React.createElement('div', { className: 'live-chart-header' },
      React.createElement('div', { className: 'live-chart-title-row' },
        React.createElement('div', { className: 'live-chart-title' },
          React.createElement('span', { className: 'live-chart-icon' }, '\uD83D\uDCC8'),
          React.createElement('h2', null, 'Live Market Chart')
        ),
        // Chart mode toggle
        React.createElement('div', { className: 'live-chart-index-pills' },
          React.createElement('button', {
            className: `live-chart-pill ${chartMode === 'index' ? 'active' : ''}`,
            onClick: () => { setChartMode('index'); setCandles([]); },
          }, '\uD83C\uDFE0 Index'),
          React.createElement('button', {
            className: `live-chart-pill ${chartMode === 'option' ? 'active' : ''}`,
            onClick: () => { setChartMode('option'); setCandles([]); },
          }, '\uD83D\uDCB0 Options')
        ),
        // Index selector
        React.createElement('div', { className: 'live-chart-index-pills' },
          ['SENSEX', 'NIFTY'].map(idx =>
            React.createElement('button', {
              key: idx,
              className: `live-chart-pill ${mode === idx ? 'active' : ''}`,
              onClick: () => { setMode(idx); setCandles([]); setSelectedSymbol(''); },
            }, idx)
          )
        )
      ),
      // Price display
      latestPrice && React.createElement('div', { className: 'live-chart-price-display' },
        React.createElement('span', { className: 'live-chart-price-label' },
          chartMode === 'option' ? selectedSymbol : mode
        ),
        React.createElement('span', { className: 'live-chart-price-value' },
          Number(latestPrice).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
        ),
        priceChange !== null && React.createElement('span', {
          className: `live-chart-price-change ${isPositive ? 'positive' : 'negative'}`
        },
          `${isPositive ? '+' : ''}${priceChange.toFixed(2)} (${isPositive ? '+' : ''}${priceChangePct.toFixed(2)}%)`
        )
      )
    ),

    // Option symbol picker
    chartMode === 'option' && React.createElement('div', { className: 'live-chart-symbol-bar' },
      React.createElement('input', {
        className: 'live-chart-symbol-search',
        type: 'text',
        placeholder: `Search ${mode} options (e.g., 84000CE)...`,
        value: symbolSearch,
        onChange: e => setSymbolSearch(e.target.value),
      }),
      React.createElement('div', { className: 'live-chart-symbol-list' },
        loadingSymbols
          ? React.createElement('span', { className: 'live-chart-updated' }, 'Loading symbols...')
          : filteredSymbols.length === 0
            ? React.createElement('span', { className: 'live-chart-updated' }, 'No symbols found')
            : filteredSymbols.map(s =>
                React.createElement('button', {
                  key: s.symbol,
                  className: `live-chart-symbol-btn ${selectedSymbol === s.symbol ? 'active' : ''}`,
                  onClick: () => { setSelectedSymbol(s.symbol); setCandles([]); },
                  title: s.ltp ? `LTP: ${Number(s.ltp).toFixed(2)}` : '',
                },
                  React.createElement('span', { className: 'live-chart-symbol-name' }, formatSymbolShort(s.symbol, mode)),
                  s.ltp != null && React.createElement('span', { className: 'live-chart-symbol-ltp' },
                    Number(s.ltp).toFixed(2)
                  )
                )
              )
      )
    ),

    // Toolbar
    React.createElement('div', { className: 'live-chart-toolbar' },
      React.createElement('div', { className: 'live-chart-intervals' },
        intervals.map(iv =>
          React.createElement('button', {
            key: iv.value,
            className: `live-chart-interval-btn ${interval === iv.value ? 'active' : ''}`,
            onClick: () => { setInterval_(iv.value); setCandles([]); },
          }, iv.label)
        )
      ),
      React.createElement('div', { className: 'live-chart-controls' },
        React.createElement('label', { className: 'live-chart-toggle' },
          React.createElement('input', {
            type: 'checkbox', checked: autoRefresh,
            onChange: e => setAutoRefresh(e.target.checked),
          }),
          React.createElement('span', { className: 'live-chart-toggle-slider' }),
          React.createElement('span', { className: 'live-chart-toggle-label' }, 'Auto-refresh')
        ),
        autoRefresh && React.createElement('span', { className: 'live-chart-live-dot' }),
        React.createElement('button', {
          className: 'live-chart-refresh-btn',
          onClick: () => fetchCandles(false), disabled: loading,
        }, '\u21BB'),
        lastUpdated && React.createElement('span', { className: 'live-chart-updated' },
          lastUpdated.toLocaleTimeString('en-IN', { hour: '2-digit', minute: '2-digit', second: '2-digit' })
        )
      )
    ),

    // Chart
    React.createElement('div', { className: 'live-chart-container' },
      loading && candles.length === 0
        ? React.createElement('div', { className: 'live-chart-loading' },
            React.createElement('div', { className: 'live-chart-spinner' }),
            React.createElement('span', null, 'Loading chart data...')
          )
        : error
          ? React.createElement('div', { className: 'live-chart-error' },
              React.createElement('span', null, '\u26A0\uFE0F'), React.createElement('span', null, error)
            )
          : candles.length === 0
            ? React.createElement('div', { className: 'live-chart-empty' },
                React.createElement('span', { style: { fontSize: '48px' } }, '\uD83D\uDCC9'),
                React.createElement('h3', null,
                  chartMode === 'option' && !selectedSymbol
                    ? 'Select an Option Symbol'
                    : 'No Data Available'),
                React.createElement('p', null,
                  chartMode === 'option' && !selectedSymbol
                    ? 'Pick a CE/PE strike from the symbol bar above.'
                    : 'Market data will appear here during trading hours.')
              )
            : React.createElement('div', { ref: chartContainerRef, className: 'live-chart-canvas' })
    ),

    // Stats bar
    candles.length > 0 && React.createElement('div', { className: 'live-chart-stats' },
      React.createElement(LiveChartStat, { label: 'Open', value: candles[0]?.open }),
      React.createElement(LiveChartStat, { label: 'High', value: Math.max(...candles.map(c => Number(c.high))) }),
      React.createElement(LiveChartStat, { label: 'Low', value: Math.min(...candles.map(c => Number(c.low))) }),
      React.createElement(LiveChartStat, { label: 'Close', value: candles[candles.length - 1]?.close }),
      React.createElement(LiveChartStat, { label: 'Candles', value: candles.length, isCount: true }),
      React.createElement(LiveChartStat, { label: 'Interval', value: `${interval}m`, isCount: true }),
      chartMode === 'option' && React.createElement(LiveChartStat, { label: 'Source', value: 'Parquet', isCount: true })
    )
  );
}

function LiveChartStat({ label, value, isCount }) {
  if (value == null) return null;
  const formatted = isCount
    ? value
    : Number(value).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  return React.createElement('div', { className: 'live-chart-stat' },
    React.createElement('span', { className: 'live-chart-stat-label' }, label),
    React.createElement('span', { className: 'live-chart-stat-value' }, formatted)
  );
}

// Shorten option symbol for display: "SENSEX2521284000CE" → "84000 CE"
function formatSymbolShort(symbol, mode) {
  if (!symbol) return symbol;
  const prefix = mode || 'SENSEX';
  let rest = symbol;
  if (rest.startsWith(prefix)) rest = rest.substring(prefix.length);
  // Extract strike + type from end: "2521284000CE" → "84000 CE"
  const match = rest.match(/(\d+)(CE|PE)$/i);
  if (match) return `${match[1]} ${match[2].toUpperCase()}`;
  return symbol;
}
