const countryMeta = [
  { code: "BR", label: "巴西", names: ["Brazil", "巴西"], point: [-51.93, -14.24] },
  { code: "EG", label: "埃及", names: ["Egypt", "埃及"], point: [30.8, 26.82] },
  { code: "ID", label: "印度尼西亚", names: ["Indonesia", "印度尼西亚"], point: [113.92, -0.79] },
  { code: "IN", label: "印度", names: ["India", "印度"], point: [78.96, 20.59] },
  { code: "TH", label: "泰国", names: ["Thailand", "泰国"], point: [100.99, 15.87] },
  { code: "TR", label: "土耳其", names: ["Turkey", "土耳其"], point: [35.24, 38.96] },
  { code: "US", label: "美国", names: ["United States", "USA", "United States of America", "美国"], point: [-95.71, 37.09] },
  { code: "VN", label: "越南", names: ["Vietnam", "Viet Nam", "越南"], point: [108.28, 14.06] }
];

const metaByName = new Map();
const metaByCode = new Map();

for (const item of countryMeta) {
  metaByCode.set(item.code, item);
  for (const name of item.names) {
    metaByName.set(normalizeKey(name), item);
  }
}

export function resolveCountryMeta({ code, name }) {
  const fromCode = code ? metaByCode.get(String(code).trim().toUpperCase()) : null;
  if (fromCode) {
    return fromCode;
  }
  return metaByName.get(normalizeKey(name)) || null;
}

export function countryFlag(code) {
  const normalized = String(code || "").trim().toUpperCase();
  if (!/^[A-Z]{2}$/.test(normalized)) {
    return "";
  }
  return Array.from(normalized)
    .map((char) => String.fromCodePoint(127397 + char.charCodeAt(0)))
    .join("");
}

export function stripCountryFlagPrefix(value) {
  return String(value || "").replace(/^(?:\s*[\u{1F1E6}-\u{1F1FF}]{2})+\s*/u, "").trim();
}

function normalizeKey(value) {
  return String(value || "").trim().toLowerCase();
}
