import { defineStore } from 'pinia'

export const useThemeStore = defineStore('theme', {
    state: () => ({
        currentTheme: 'theme-white', // 默认浅色主题
        isThemeChanging: false // 主题切换loading状态
    }),

    getters: {
        isDarkTheme: (state) => state.currentTheme === 'theme-blue',
        isLightTheme: (state) => state.currentTheme === 'theme-white'
    },

    actions: {
        // 设置主题
        async setTheme(theme: 'theme-blue' | 'theme-white') {
            if (this.currentTheme === theme) return

            this.isThemeChanging = true

            // 使用 setTimeout 来确保 loading 状态显示
            await new Promise((resolve) => setTimeout(resolve, 50))

            this.currentTheme = theme
            this.applyTheme()

            // 等待主题应用完成后隐藏 loading
            await new Promise((resolve) => setTimeout(resolve, 500))
            this.isThemeChanging = false
        },

        // 切换主题
        async toggleTheme() {
            const newTheme = this.currentTheme === 'theme-blue' ? 'theme-white' : 'theme-blue'
            await this.setTheme(newTheme)
        },

        // 应用主题到 DOM
        applyTheme() {
            const html = document.documentElement

            // 移除旧的主题类
            html.classList.remove('theme-blue', 'theme-white')

            // 添加新的主题类
            html.classList.add(this.currentTheme)
        },

        // 初始化主题（从缓存读取）
        initTheme() {
            const savedTheme = localStorage.getItem('app-theme')
            if (savedTheme && (savedTheme === 'theme-blue' || savedTheme === 'theme-white')) {
                this.currentTheme = savedTheme
            }
            this.applyTheme()
        }
    },

    persist: {
        storage: localStorage,
        key: 'theme-store',
        pick: ['currentTheme']
    }
})
