export type Theme = 'light' | 'dark' | 'blue'

export const THEMES: { value: Theme; label: string }[] = [
  { value: 'light', label: '라이트' },
  { value: 'dark', label: '다크' },
  { value: 'blue', label: '블루' },
]

const STORAGE_KEY = 'bizcare_theme'
const VALID: Theme[] = ['light', 'dark', 'blue']

export function loadTheme(): Theme {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    if (raw && (VALID as string[]).includes(raw)) return raw as Theme
  } catch {
    /* private mode */
  }
  return 'light'
}

export function applyTheme(theme: Theme): void {
  const el = document.documentElement
  el.classList.remove('theme-light', 'theme-dark', 'theme-blue')
  el.classList.add(`theme-${theme}`)
}

export function saveTheme(theme: Theme): void {
  try {
    localStorage.setItem(STORAGE_KEY, theme)
  } catch {
    /* quota */
  }
}

export function setTheme(theme: Theme): void {
  applyTheme(theme)
  saveTheme(theme)
}

export const THEME_PRIMARY: Record<Theme, string> = {
  light: '#2563eb',
  dark: '#7aa2f7',
  blue: '#1e8ad4',
}

/** G2 / @ant-design/plots 차트용 테마 토큰 */
export function chartPlotTheme(theme: Theme) {
  const dark = theme !== 'light'
  return {
    type: dark ? ('classicDark' as const) : ('classic' as const),
    barColor: theme === 'light' ? '#91caff' : THEME_PRIMARY[theme],
    labelFill: dark ? (theme === 'blue' ? '#e8f4ff' : '#c0caf5') : '#595959',
    successStroke: dark ? (theme === 'blue' ? '#5ce0a0' : '#9ece6a') : '#52c41a',
    axisLabelFill: dark ? (theme === 'blue' ? '#8fbbe0' : '#8a93b8') : '#595959',
    gridStroke: dark ? (theme === 'blue' ? 'rgba(94,181,255,0.18)' : 'rgba(122,162,247,0.18)') : '#e5e7eb',
  }
}

/** 첫화면 대시보드 차트·미니차트 액센트 */
export function homeAccentColors(theme: Theme) {
  const plot = chartPlotTheme(theme)
  const primary = THEME_PRIMARY[theme]
  const success = plot.successStroke
  const secondary = theme === 'light' ? '#0ea5e9' : theme === 'blue' ? '#8fbbe0' : '#7dcfff'
  return {
    plot,
    sparkPhone: theme === 'light' ? '#14b8a6' : success,
    sparkUsim: theme === 'light' ? '#3b82f6' : primary,
    waveOut: theme === 'light' ? '#38bdf8' : primary,
    waveFare: secondary,
    columnFill: theme === 'light' ? '#2563eb' : primary,
    areaStroke: success,
    areaFill:
      theme === 'light'
        ? 'rgba(22,163,74,0.28)'
        : theme === 'blue'
          ? 'rgba(92,224,160,0.28)'
          : 'rgba(158,206,106,0.28)',
  }
}
