import Vue from "vue"
import VueI18n from "vue-i18n"
import Cookies from "js-cookie"
import zhCN from "@/lang/zh-CN"
import bo from "@/lang/bo"

Vue.use(VueI18n)

export const LOCALE_COOKIE = "locale"
export const SUPPORT_LOCALES = ["zh-CN", "bo"]

export function getInitialLocale() {
  const v = Cookies.get(LOCALE_COOKIE)
  return SUPPORT_LOCALES.includes(v) ? v : "zh-CN"
}

function syncDom(locale) {
  if (typeof document === "undefined") {
    return
  }
  const el = document.documentElement
  el.setAttribute("lang", locale === "bo" ? "bo" : "zh-CN")
  el.classList.toggle("lang-bo", locale === "bo")
}

const i18n = new VueI18n({
  locale: getInitialLocale(),
  fallbackLocale: "zh-CN",
  silentTranslationWarn: true,
  messages: {
    "zh-CN": zhCN,
    bo
  }
})

syncDom(i18n.locale)

export function setLocale(locale) {
  if (!SUPPORT_LOCALES.includes(locale)) {
    return
  }
  Cookies.set(LOCALE_COOKIE, locale, { expires: 365 })
  i18n.locale = locale
  syncDom(locale)
}

export default i18n
