import { toWesternDigits } from "@/lib/digits";

/**
 * What a digits-only field keeps of what was typed or pasted.
 *
 * Arabic is the default UI language, and an Arabic keyboard (phone or desktop)
 * types Arabic-Indic digits «٠١٢…». A bare `/\D/g` strip treats those as
 * non-digits — `\d` only matches ASCII 0–9 — so a phone number, a date or a
 * time typed on an Arabic keyboard silently vanished from the box. They are
 * converted to ASCII first, which is also what the API expects.
 */
export function keepDigits(value: string, maxLength?: number): string {
  const digits = toWesternDigits(value).replace(/\D/g, "");
  return typeof maxLength === "number" ? digits.slice(0, maxLength) : digits;
}

/**
 * What a letters-only (name) field keeps: letters of any script, combining
 * marks and spaces. It used to be `/[^A-Za-z\s]/`, which stripped every Arabic
 * letter — a guardian's name could not be typed in Arabic at all, on a
 * platform whose default language is Arabic (PDF p.8, p.37).
 */
export function keepLetters(value: string): string {
  return value.replace(/[^\p{L}\p{M}\s]/gu, "");
}
