import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useLangStore = defineStore('lang', () => {
  // 状态
  const langList = ref([
    {
      type: 'en',
      value: 'English',
      dir: 'ltr',
    },
    // {
    //   type: 'zh',
    //   value: '中文',
    //   dir: 'ltr',
    // },
    {
      type: 'ar',
      value: 'اللغة العربية',
      dir: 'rtl',
    },
    {
      type: 'tr',
      value: 'Türkçe',
      dir: 'ltr',
    },
    {
      type: 'bn',
      value: 'বাংলা',
      dir: 'ltr',
    },
    {
      type: 'pt',
      value: 'Português',
      dir: 'ltr',
    },
  ])

  const selectedLang = ref(langList.value[0])

  // Getter
  const currentLanguage = computed(() => selectedLang.value)
  const availableLanguages = computed(() => langList.value)

  // Action
  const setLanguage = (lang) => {
    selectedLang.value = lang
    localStorage.setItem('preferred-language', lang.type)
  }

  // 初始化语言
  const initLanguage = () => {
    const savedLang = localStorage.getItem('preferred-language')
    if (savedLang) {
      const lang = langList.value.find((item) => item.type === savedLang)
      if (lang) {
        setLanguage(lang)
        return
      }
    }

    // 根据浏览器语言自动检测
    const browserLang = navigator.language.split('-')[0]
    const detectedLang = langList.value.find((item) => item.type === browserLang)
    if (detectedLang) {
      setLanguage(detectedLang)
    }
  }

  return {
    selectedLang,
    langList,
    currentLanguage,
    availableLanguages,
    setLanguage,
    initLanguage,
  }
})
