import type { IndicatorConfig, Theme, ChartType, Timeframe, MainChartStyle } from '../types';

interface ChartState {
  version:        number;
  symbol:         string;
  timeframe:      Timeframe;
  chartType:      ChartType;
  theme:          Theme;
  indicators:     IndicatorConfig[];
  watchlist:      string[];
  alertPrices:    number[];
  mainChartStyle?: MainChartStyle;
}

const KEY          = 'trading_chart_state';
const CUR_VERSION  = 8;   // v8: 기본 지표 제거 — 초기 로딩 시 캔들차트만 표시

/** 기본 보조지표 없음 — 처음 로딩 시 캔들차트만 표시 */
const DEFAULT_INDICATORS: IndicatorConfig[] = [];

const DEFAULT_WATCHLIST = [
  'KRW-BTC', 'KRW-ETH', 'KRW-XRP', 'KRW-SOL', 'KRW-DOGE',
  'KRW-ADA', 'KRW-AVAX', 'KRW-DOT',
];

/**
 * 절대적 최후 fallback 기본값.
 * 우선순위: DB(gc_app_settings) > localStorage > 이 값.
 * 타임프레임을 '1h' 에서 '1D' 로 통일 (ChartSlot 기본값과 일치).
 */
const DEFAULT_STATE: ChartState = {
  version:     CUR_VERSION,
  symbol:      'KRW-BTC',
  timeframe:   '1D',
  chartType:   'candlestick',
  theme:       'dark',
  indicators:  DEFAULT_INDICATORS,
  watchlist:   DEFAULT_WATCHLIST,
  alertPrices: [],
};

export function saveState(state: Partial<ChartState>): void {
  try {
    const existing = loadState();
    localStorage.setItem(KEY, JSON.stringify({ ...existing, ...state, version: CUR_VERSION }));
  } catch { /* ignore */ }
}

export function loadState(): ChartState {
  try {
    const raw = localStorage.getItem(KEY);
    if (raw) {
      const parsed = JSON.parse(raw) as ChartState;
      // 버전이 다르면 기본값으로 재설정 (마이그레이션)
      if (parsed.version !== CUR_VERSION) {
        localStorage.removeItem(KEY);
        return DEFAULT_STATE;
      }
      return parsed;
    }
  } catch { /* ignore */ }
  return DEFAULT_STATE;
}

export function clearState(): void {
  localStorage.removeItem(KEY);
}

export const DEFAULT_MAIN_CHART_STYLE: MainChartStyle = {
  upColor:         '#ff6b6b',
  downColor:       '#4dabf7',
  borderUpColor:   '#ff6b6b',
  borderDownColor: '#4dabf7',
  wickUpColor:     '#ff6b6b',
  wickDownColor:   '#4dabf7',
};

export { DEFAULT_INDICATORS };
