const COLOR_MODES = ['light', 'dark']
const el = document.querySelector('.js-theme-switch')


function setColorThemeMode(t) {

  let e = document.documentElement;
  e.setAttribute("data-color-mode", t);
  let a = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches
    , s = t;
  "auto" === t && (s = a ? "dark" : "light"),
    "light" === s ? (e.classList.remove("dark"),
      e.classList.add("light")) : (e.classList.remove("light"),
        e.classList.add("dark"))
}

function rotateColorMode() {
  let index = getModeIndex()
  index += 1
  if (!COLOR_MODES[index]) {
    index = 0
  }
  const mode = COLOR_MODES[index]
  setColorThemeMode(mode)
  localStorage['_theme'] = mode
  updateLabel(mode)
}

function getModeIndex() {
  return COLOR_MODES.indexOf(
    document.documentElement.getAttribute('data-color-mode') || 'light'
  )
}

function updateLabel(mode) {
  const label = el.getAttribute('data-aria-' + mode)
  el.setAttribute('aria-label', label)
}

if (el) {
  // 默认第一次选择为亮色模式
  if (document.documentElement.getAttribute('data-color-mode') === 'auto') {
    setColorThemeMode('light')
  }

  el.addEventListener('click', rotateColorMode)
  updateLabel(COLOR_MODES[getModeIndex()] || 'light')
}
