import type { Router } from "vitepress"
import { SupportedLanguage } from "@src/types/language"

const SUPPORTED_LANGUAGES = Object.values(SupportedLanguage)

export const LANGUAGE_DISPLAY_NAMES: Record<SupportedLanguage, string> = {
  [SupportedLanguage.DE]: "Deutsch",
  [SupportedLanguage.EN]: "English",
  [SupportedLanguage.FR]: "Français",
  [SupportedLanguage.RU]: "Русский",
  [SupportedLanguage.ZH]: "简体中文",
}

/**
 * 语言路径前缀映射
 */
export const LANGUAGE_PREFIXES: Record<SupportedLanguage, string> = {
  [SupportedLanguage.DE]: "/de",
  [SupportedLanguage.EN]: "/en",
  [SupportedLanguage.FR]: "/fr",
  [SupportedLanguage.RU]: "/ru",
  [SupportedLanguage.ZH]: "/zh",
}

/**
 * VitePress localeIndex 到语言路径前缀的映射
 */
const LOCALE_INDEX_TO_PREFIX: Record<string, string> = {
  zh: LANGUAGE_PREFIXES[SupportedLanguage.ZH],
  de: LANGUAGE_PREFIXES[SupportedLanguage.DE],
  en: LANGUAGE_PREFIXES[SupportedLanguage.EN],
  fr: LANGUAGE_PREFIXES[SupportedLanguage.FR],
  ru: LANGUAGE_PREFIXES[SupportedLanguage.RU],
}

/**
 * 检测浏览器语言并返回对应的语言代码
 */
export function detectBrowserLanguage(lang: string | null): SupportedLanguage {
  if (!lang) {
    return SupportedLanguage.EN
  }

  for (const value of SUPPORTED_LANGUAGES) {
    if (lang.startsWith(value)) {
      return value
    }
  }

  return SupportedLanguage.EN
}

const STORAGE_KEY_LANGUAGE = "loongfansLanguageV1"

/**
 * 获取存储的语言偏好
 */
export function getStoredLanguage(): string | null {
  return localStorage.getItem(STORAGE_KEY_LANGUAGE)
}

/**
 * 存储语言偏好
 */
export function setStoredLanguage(lang: string) {
  localStorage.setItem(STORAGE_KEY_LANGUAGE, lang)
}

export function removeStoredLanguage() {
  return localStorage.removeItem(STORAGE_KEY_LANGUAGE)
}

/**
 * 根据 VitePress 的 localeIndex 获取语言路径前缀
 * @param localeIndex VitePress useData() 返回的 localeIndex
 * @returns 语言路径前缀，如 '/en' 或 ''
 */
export function getLocalePrefix(localeIndex: string): string {
  return LOCALE_INDEX_TO_PREFIX[localeIndex] || ""
}

/**
 * 根据语言偏好重定向，只在访问不带前缀的路径时调用
 */
export function handleRedirect(router: Router) {
  router.go(
    getLocaleUrl(detectBrowserLanguage(navigator.language), router.route.path),
  )
}

/**
 * @param lang Accepts string for vue-i18n compatibility (useI18n().locale is typed as string)
 * @param url URL starts with `/`
 */
export function getLocaleUrl(lang: SupportedLanguage | string, url: string) {
  return LANGUAGE_PREFIXES[lang as SupportedLanguage] + normalizeUrl(url)
}

/**
 * @param url URL starts with `/`
 */
function normalizeUrl(url: string) {
  for (const lang of SUPPORTED_LANGUAGES) {
    if (url === LANGUAGE_PREFIXES[lang]) return "/"
    const prefix = LANGUAGE_PREFIXES[lang] + "/"
    if (url === prefix) return "/"
    if (url.startsWith(prefix)) return "/" + url.replace(prefix, "")
  }
  return url
}
