import { defineStore } from 'pinia';
import i18n from '@/i18n'; // 导入 i18n 实例

// 导入 Element Plus 语言包
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import en from 'element-plus/es/locale/lang/en';

// 语言包映射
const elLocaleMap = {
  'zh-CN': zhCn,
  en: en,
};

const LANG_KEY = 'APP_CURRENT_LANG';

const getInitialLang = () => {
  const savedLang = localStorage.getItem(LANG_KEY);
  if (savedLang && ['zh-CN', 'en'].includes(savedLang)) {
    return savedLang;
  }
  const browserLang = navigator.language || 'zh-CN';
  return browserLang.toLowerCase().startsWith('en') ? 'en' : 'zh-CN';
};

export const useLangStore = defineStore('lang', {
  state: () => {
    const initialLang = getInitialLang();
    return {
      currentLang: initialLang,
      elLocale: elLocaleMap[initialLang],
    };
  },
  actions: {
    changeLang(lang) {
      if (!['zh-CN', 'en'].includes(lang)) return;

      this.currentLang = lang;
      this.elLocale = elLocaleMap[lang];
      i18n.global.locale.value = lang; // 正确更新 i18n 实例的 locale
      localStorage.setItem(LANG_KEY, lang);
      this.updateDynamicTitle();
    },
    updateDynamicTitle() {
      // 动态更新页面标题
      document.title = i18n.global.t('common.title');
    },
    // 初始化时设置语言
    initializeLang() {
      const initialLang = this.currentLang;
      i18n.global.locale.value = initialLang;
      this.updateDynamicTitle();
    }
  },
});