import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { SetWindowTitleBarColor } from '../wailsjs/v3-bindings/u-desk/app'

type Theme = 'light' | 'dark'

const THEME_STORAGE_KEY = 'app-theme'

// 标题栏颜色（0x00BBGGRR）
const TITLE_BAR_LIGHT = 0xF0F0F0  // #F0F0F0 近白
const TITLE_BAR_DARK  = 0x2D2D2D   // #2D2D2D 深灰

/**
 * 主题管理 Store
 * 统一管理应用主题（亮色/暗色）及标题栏颜色
 */
export const useThemeStore = defineStore('theme', () => {
  // ==================== 状态 ====================
  const theme = ref<Theme>('light')
  let systemThemeListener: (() => void) | null = null

  // ==================== 计算属性 ====================
  const isDark = computed(() => theme.value === 'dark')
  const tooltipText = computed(() =>
    isDark.value ? '切换到亮色主题' : '切换到夜间主题'
  )

  // ==================== 核心方法 ====================
  /**
   * 应用主题到 DOM + 同步标题栏颜色
   */
  const applyTheme = (newTheme: Theme) => {
    theme.value = newTheme

    // 更新 DOM 属性
    const method = newTheme === 'dark' ? 'setAttribute' : 'removeAttribute'
    document.body[method]('arco-theme', 'dark')

    // 同步 Windows 原生标题栏颜色 + 主题模式
    try {
      const color = newTheme === 'dark' ? TITLE_BAR_DARK : TITLE_BAR_LIGHT
      SetWindowTitleBarColor(color, newTheme === 'dark')
    } catch { /* 非 Windows 环境忽略 */ }

    // 持久化
    localStorage.setItem(THEME_STORAGE_KEY, newTheme)
  }

  /**
   * 切换主题
   */
  const toggleTheme = () => {
    const newTheme: Theme = theme.value === 'light' ? 'dark' : 'light'
    applyTheme(newTheme)
  }

  /**
   * 初始化主题（应用启动时调用）
   */
  const initTheme = () => {
    // 加载保存的主题或使用系统偏好
    const savedTheme = localStorage.getItem(THEME_STORAGE_KEY) as Theme
    const isValidTheme = savedTheme === 'light' || savedTheme === 'dark'

    if (isValidTheme) {
      applyTheme(savedTheme)
    } else {
      const prefersDark = window.matchMedia?.('(prefers-color-scheme: dark)').matches
      applyTheme(prefersDark ? 'dark' : 'light')
    }

    // 监听系统主题变化（仅在未手动设置时）
    if (!window.matchMedia) return

    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    const handleChange = (e: MediaQueryListEvent) => {
      if (!localStorage.getItem(THEME_STORAGE_KEY)) {
        applyTheme(e.matches ? 'dark' : 'light')
      }
    }

    mediaQuery.addEventListener('change', handleChange)
    systemThemeListener = () => mediaQuery.removeEventListener('change', handleChange)
  }

  // ==================== 返回 ====================
  return {
    // 状态
    theme,

    // 计算属性
    isDark,
    tooltipText,

    // 方法
    toggleTheme,
    initTheme
  }
})
