/* eslint-disable no-control-regex */
const INVISIBLE_CONTROL_CHARS = new RegExp(
  "[\\u0000-\\u001F\\u007F-\\u009F\\u00AD\\u061C\\u180E\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u206F\\uFEFF]",
  "g",
);

export function cleanOptionLabel(value: string | null | undefined) {
  return String(value || "")
    .replace(INVISIBLE_CONTROL_CHARS, "")
    .replace(/\u00A0/g, " ")
    .replace(/\s+/g, " ")
    .trim();
}

export function normalizeOptionKey(value: string | null | undefined) {
  return cleanOptionLabel(value)
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .toLowerCase()
    .replace(/[^\p{L}\p{N}]+/gu, " ")
    .trim();
}

export function canonicalOptionLabel(value: string | null | undefined) {
  const cleanValue = cleanOptionLabel(value);
  const key = normalizeOptionKey(cleanValue);

  if (
    ["republica dominicana", "rep dominicana", "rep dom", "rep dom lizbeth", "dominicana"].includes(
      key,
    )
  )
    return "Republica Dominicana";

  return cleanValue;
}

export function dedupeOptions(values: Array<string | null | undefined>) {
  const unique = new Map<string, string>();

  for (const value of values) {
    const cleanValue = canonicalOptionLabel(value);
    if (!cleanValue) continue;

    const key = normalizeOptionKey(cleanValue);
    if (!key) continue;

    if (!unique.has(key)) {
      unique.set(key, cleanValue);
    }
  }

  return Array.from(unique.values());
}

export function ensureOption(options: string[], value: string | null | undefined) {
  const uniqueOptions = dedupeOptions(options);
  const current = canonicalOptionLabel(value);

  if (!current) return uniqueOptions;

  const currentKey = normalizeOptionKey(current);
  const exists = uniqueOptions.some((option) => normalizeOptionKey(option) === currentKey);

  return exists ? uniqueOptions : [current, ...uniqueOptions];
}
