import { defineStore } from 'pinia'

interface ThemeState {
  theme: string
  isManualChange: boolean
}
export const useThemeStore = defineStore('theme', {
  state: (): ThemeState => ({
    theme: localStorage.getItem('theme') || 'light',
    isManualChange: JSON.parse(localStorage.getItem('isManualChange')) || false
  }),
  actions: {
    toggleTheme(theme: string, isManualChange = false) {
      localStorage.setItem('theme', theme)
      this.theme = theme

      const html = document.documentElement
      if (html.classList.contains('dark') && theme === 'light') {
        unloadDarkTheme()
        html.classList.remove('dark')
      } else if (!html.classList.contains('dark') && theme === 'dark') {
        loadDarkTheme()
        html.classList.add('dark')
      }
      // 主动修改主题后，不再跟随系统设置
      if (isManualChange) {
        localStorage.setItem('isManualChange', JSON.stringify(isManualChange))
        this.isManualChange = isManualChange
      }
    }
  }
})

// 动态加载暗黑主题
async function loadDarkTheme() {
  await import('element-plus/theme-chalk/dark/css-vars.css') // 动态导入暗黑主题
}
// 动态移除暗黑主题
function unloadDarkTheme() {
  const darkThemeStylesheet = document.getElementById('dark-theme-style')
  if (darkThemeStylesheet) {
    darkThemeStylesheet.remove()
  }
}
