import { ref, computed } from "vue";
import { useI18n } from "vue-i18n";
import { useLangStore } from "@/stores/lang";

const LANG_OPTIONS = [
  { value: "zhCN", label: "中文(简体)" },
  { value: "zhTW", label: "中文(繁體)" },
  { value: "enUS", label: "English" },
];

const LANG_MAP = {
  zhCN: "中文(简体)",
  zhTW: "中文(繁體)",
  enUS: "English",
};

export function useLanguage() {
  const store = useLangStore();
  const { locale } = useI18n();

  const currentLangKey = ref(
    store.language || localStorage.getItem("lang") || "zhCN",
  );

  const currentLangValue = computed({
    get: () => LANG_MAP[currentLangKey.value],
    set: (lang) => changeLang(lang),
  });

  const changeLang = (lang) => {
    if (!lang || currentLangKey.value === lang) return;
    currentLangKey.value = lang;
    locale.value = lang;
    try {
      store.changeLang(lang);
    } catch (error) {
      console.warn("change language failed:", error);
    }
    // 如果你框架有全局通知微应用可以发事件
    // window.dispatchEvent(new CustomEvent('app-lang-change', { detail: lang }))
  };

  return {
    langOptions: LANG_OPTIONS,
    currentLang: currentLangValue,
    currentLangKey,
    changeLang,
  };
}
