import { ref, watch, onMounted } from 'vue'

const STORAGE_KEY = 'hud_theme'

/** 供图表等订阅，与 data-theme / html.dark 同步 */
export const hudThemeRef = ref('light')

function applyDom() {
  const root = document.documentElement
  root.dataset.theme = hudThemeRef.value
  root.classList.toggle('dark', hudThemeRef.value === 'dark')
}

if (typeof window !== 'undefined') {
  const saved = localStorage.getItem(STORAGE_KEY)
  if (saved === 'dark' || saved === 'light') {
    hudThemeRef.value = saved
  }
  applyDom()
}

let watchStarted = false

function startWatch() {
  if (watchStarted) return
  watchStarted = true
  watch(hudThemeRef, (v) => {
    localStorage.setItem(STORAGE_KEY, v)
    applyDom()
  })
}

export function useHudTheme() {
  onMounted(() => {
    startWatch()
  })

  function toggleTheme() {
    hudThemeRef.value = hudThemeRef.value === 'dark' ? 'light' : 'dark'
  }

  return { theme: hudThemeRef, toggleTheme }
}
