;(() => {
  const KEY = 'he_theme'
  const norm = (v) => (v === 'dark' || v === 'light' ? v : '')
  const getStored = () => {
    try { return norm(globalThis.localStorage?.getItem?.(KEY) || '') } catch { return '' }
  }
  const setStored = (t) => {
    try { globalThis.localStorage?.setItem?.(KEY, t) } catch {}
  }
  const getMode = () => getStored() || 'light'
  const getCurrent = (mode) => {
    const nextMode = norm(mode) || getMode()
    return nextMode === 'dark' ? 'dark' : 'light'
  }
  const applyTheme = (mode) => {
    const nextMode = norm(mode) || getMode()
    const theme = getCurrent(nextMode)
    try {
      const el = globalThis.document?.documentElement
      if (el) {
        el.dataset.theme = theme
        el.dataset.themeMode = nextMode
        el.style.colorScheme = theme === 'dark' ? 'dark' : 'light'
      }
    } catch {}
    updateButtons(nextMode, theme)
  }
  const updateButtons = (mode, theme) => {
    const text = theme === 'dark' ? '主题：深色' : '主题：浅色'
    try {
      globalThis.document?.querySelectorAll?.('[data-theme-toggle]')?.forEach((btn) => {
        try {
          btn.setAttribute('aria-label', text)
          btn.setAttribute('title', text)
          btn.setAttribute('aria-pressed', theme === 'dark' ? 'true' : 'false')
          btn.setAttribute('data-theme-mode', mode)
        } catch {}
      })
    } catch {}
  }
  const toggleTheme = () => {
    const cur = getMode()
    const next = cur === 'light' ? 'dark' : 'light'
    setStored(next)
    applyTheme(next)
  }
  const bind = () => {
    try {
      globalThis.document?.querySelectorAll?.('[data-theme-toggle]')?.forEach((btn) => {
        try {
          btn.addEventListener('click', () => toggleTheme())
        } catch {}
      })
    } catch {}
  }
  const init = () => {
    applyTheme(getMode())
    bind()
  }
  try {
    if (globalThis.document?.readyState === 'loading') {
      globalThis.document?.addEventListener?.('DOMContentLoaded', init)
    } else {
      init()
    }
  } catch {}
})()
