import en from "./en.json"
import countryPhonecodeMap from "./phone.json"
// utils/country.ts
import zh from "./zh.json"

// 定义类型
// type Language = "zh" | "en" | "zh-CN" | "en-US"
export interface CountryItem {
  label: string
  value: string
}
interface Options {
  isFilterCN: boolean
}
type CountryMap = Record<string, string>
type PhoneCodeMap = Record<string, { countryCallingCode: string }>

// 常量和变量
export const countriesListMap = new Map<string, CountryItem[]>()
const CHINA_CODE = "CN"
export const zhCountryMap: CountryMap = zh
export const enCountryMap: CountryMap = en

// 语言映射：将不同的语言格式统一
const languageMapping: Record<string, "zh" | "en"> = {
  "zh": "zh",
  "zh-CN": "zh",
  "zh-TW": "zh",
  "zh-HK": "zh",
  "en": "en",
  "en-US": "en",
  "en-GB": "en",
  "en-AU": "en"
}

/**
 * 标准化语言代码
 */
function normalizeLanguage(lang: string): "zh" | "en" {
  const normalized = languageMapping[lang]
  return normalized || "en" // 默认使用英文
}

/**
 * 获取国家列表
 *
 * @param {string} lang - 语言代码
 * @param {Options} [options] - 选项，默认过滤中国
 * @returns {CountryItem[]} 国家列表
 */
export function getCountriesList(lang: string, options: Options = { isFilterCN: true }): CountryItem[] {
  const { isFilterCN } = options

  // 标准化语言代码
  const normalizedLang = normalizeLanguage(lang)
  const mapKey = `${normalizedLang}-${isFilterCN ? "filterCN" : "all"}`

  if (countriesListMap.has(mapKey)) {
    return countriesListMap.get(mapKey)!
  }

  const language2json: Record<"zh" | "en", CountryMap> = {
    zh: zhCountryMap,
    en: enCountryMap
  }

  const countriesMap = language2json[normalizedLang]

  // 安全检查：确保 countriesMap 是有效的对象
  if (!countriesMap || typeof countriesMap !== "object") {
    console.warn(`Invalid country map for language: ${lang}, normalized to: ${normalizedLang}`)
    return []
  }

  const list: CountryItem[] = []

  // 使用 try-catch 确保安全
  try {
    for (const [code, name] of Object.entries(countriesMap)) {
      if (isFilterCN && code === CHINA_CODE) continue
      list.push({
        label: name,
        value: code
      })
    }
  } catch (error) {
    console.error("Error processing country list:", error)
    return []
  }

  countriesListMap.set(mapKey, list)
  return list
}

/**
 * 将字符串转换为小写
 *
 * @param {string} str - 需要转换的字符串
 * @returns {string} 转换后的字符串
 */
export function valueToLowerCase(str: string): string {
  return str ? str.toLowerCase() : ""
}

/**
 * 获取国家电话区号
 *
 * @param {string} code - 国家代码
 * @returns {string} 电话区号
 */
export function getCountryPhoneCode(code: string): string {
  const phoneMap = countryPhonecodeMap as PhoneCodeMap
  return phoneMap[code]?.countryCallingCode || ""
}
