import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
// 导入 Element Plus 中英文语言包
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import en from 'element-plus/es/locale/lang/en'
import i18n from '@/locales'

// 默认语言从环境变量获取
const DEFAULT_LANG = import.meta.env.VITE_APP_LANG || 'zh-cn'

// 从 localStorage 获取初始语言
function getInitialLanguage(): string {
  try {
    const stored = localStorage.getItem('language')
    if (stored) {
      const parsed = JSON.parse(stored)
      if (parsed === 'zh-cn' || parsed === 'en') {
        return parsed
      }
    }
  } catch {
    // ignore
  }
  return DEFAULT_LANG
}

export const useAppStore = defineStore('app', () => {
  // 侧边栏状态
  const sidebarOpened = ref(true)
  const loading = ref(false)

  // 语言：使用简单的 ref，手动处理持久化
  const language = ref(getInitialLanguage())
  const size = ref<'default' | 'small' | 'large'>('default')

  /**
   * 根据语言标识读取对应的 Element Plus 语言包
   */
  const locale = computed(() => {
    if (language?.value === 'zh-cn') {
      return zhCn
    }
    return en
  })

  function toggleSidebar() {
    sidebarOpened.value = !sidebarOpened.value
  }

  function closeSidebar() {
    sidebarOpened.value = false
  }

  function openSidebar() {
    sidebarOpened.value = true
  }

  function setLoading(value: boolean) {
    loading.value = value
  }

  /**
   * 切换语言
   */
  function changeLanguage(val: string) {
    language.value = val
    i18n.global.locale.value = val
    // 手动保存到 localStorage
    try {
      localStorage.setItem('language', JSON.stringify(val))
    } catch {
      // ignore
    }
  }

  /**
   * 设置组件尺寸
   */
  function setSize(val: 'default' | 'small' | 'large') {
    size.value = val
  }

  return {
    sidebarOpened,
    loading,
    language,
    locale,
    size,
    toggleSidebar,
    closeSidebar,
    openSidebar,
    setLoading,
    changeLanguage,
    setSize
  }
})
