/**
 * 캔들차트 상단 OHLCV·지표 범례 (tv-legend)
 */
import React from 'react';
import type { WsStatus } from '../hooks/useUpbitData';
import type { ChartMode, IndicatorConfig, LegendData } from '../types';
import type { ChartLegendVisibility } from '../types/chartLegend';
import { formatPrice } from '../utils/dataGenerator';
import { getIndicatorDef, getIndicatorChartTitle } from '../utils/indicatorRegistry';
import { formatBbLegendLabel } from '../utils/bollingerConfig';

const WsBadge: React.FC<{ status: WsStatus; isUpbit: boolean }> = ({ status, isUpbit }) => {
  if (!isUpbit) return null;
  const map: Record<WsStatus, { dot: string; label: string }> = {
    connecting:   { dot: 'dot-yellow', label: '연결 중...' },
    connected:    { dot: 'dot-lime',   label: '실시간' },
    disconnected: { dot: 'dot-red',    label: '재연결 중' },
    error:        { dot: 'dot-red',    label: '오류' },
  };
  const { dot, label } = map[status];
  return <span className={`ws-badge ${dot}`}><span className="ws-dot" />{label}</span>;
};

export interface ChartLegendBarProps {
  visibility: ChartLegendVisibility;
  symbol: string;
  timeframe: string;
  useUpbit: boolean;
  wsStatus: WsStatus;
  mode: ChartMode;
  currentBar: LegendData | null;
  isUp: boolean;
  dailyChange: number;
  dailyChangePct: number;
  indicators: IndicatorConfig[];
  legend: LegendData | null;
}

export const ChartLegendBar: React.FC<ChartLegendBarProps> = ({
  visibility: v,
  symbol,
  timeframe,
  useUpbit,
  wsStatus,
  mode,
  currentBar,
  isUp,
  dailyChange,
  dailyChangePct,
  indicators,
  legend,
}) => {
  const showOhlc = currentBar && (v.open || v.high || v.low || v.close || v.change);
  const showAny =
    v.symbol || v.timeframe || (useUpbit && v.liveStatus) || (mode === 'trading' && v.tradingBadge)
    || showOhlc || (v.indicators && indicators.length > 0);

  if (!showAny) return null;

  return (
    <div className="tv-legend">
      {v.symbol && (
        <span className="tv-legend-sym">
          <span className="tv-legend-dot" style={{ background: isUp ? 'var(--up)' : 'var(--down)' }} />
          {symbol}
        </span>
      )}
      {v.timeframe && <span className="tv-legend-tf">· {timeframe}</span>}
      {useUpbit && v.liveStatus && <WsBadge status={wsStatus} isUpbit={true} />}
      {mode === 'trading' && v.tradingBadge && <span className="tv-legend-badge trading">✏</span>}
      {showOhlc && (
        <span className="tv-legend-ohlcv">
          {v.open && (
            <span>O <b className={isUp ? 'up' : 'down'}>{formatPrice(currentBar!.open)}</b></span>
          )}
          {v.high && (
            <span>H <b className="up">{formatPrice(currentBar!.high)}</b></span>
          )}
          {v.low && (
            <span>L <b className="down">{formatPrice(currentBar!.low)}</b></span>
          )}
          {v.close && (
            <span>C <b className={isUp ? 'up' : 'down'}>{formatPrice(currentBar!.close)}</b></span>
          )}
          {v.change && (
            <span className={`tv-legend-chg ${isUp ? 'up' : 'down'}`}>
              {isUp ? '▲' : '▼'} {formatPrice(Math.abs(dailyChange))} ({Math.abs(dailyChangePct).toFixed(2)}%)
            </span>
          )}
        </span>
      )}
      {v.indicators && indicators.map(ind => {
        const def = getIndicatorDef(ind.type);
        const vals = legend?.indicatorValues?.[ind.type];
        const plots = ind.plots ?? def?.plots ?? [];
        const label = ind.type === 'BollingerBands'
          ? formatBbLegendLabel(ind.params ?? {})
          : getIndicatorChartTitle(ind.type);
        const fmtVal = (n: number) =>
          Math.abs(n) >= 1000
            ? n.toLocaleString('ko-KR', { maximumFractionDigits: 1 })
            : n.toFixed(2);
        return def ? (
          <span key={ind.id} className="tv-legend-ind">
            <span className="tv-legend-ind-name">{label}</span>
            {v.indicatorValues && vals && vals.length > 0 && (
              <span className="tv-legend-ind-vals">
                {vals.map((n, i) =>
                  Number.isFinite(n) ? (
                    <b
                      key={i}
                      style={{ color: (plots[i]?.color ?? def.plots?.[i]?.color ?? '#42A5F5').slice(0, 7) }}
                    >
                      {fmtVal(n)}
                    </b>
                  ) : null,
                )}
              </span>
            )}
          </span>
        ) : null;
      })}
    </div>
  );
};

export default ChartLegendBar;
