/** Persian/Arabic-Indic digits → ASCII */
function toAsciiDigits(value: string): string {
  return value.replace(/[۰-۹٠-٩]/g, (ch) => {
    const code = ch.charCodeAt(0);
    if (code >= 0x06f0 && code <= 0x06f9) return String(code - 0x06f0);
    if (code >= 0x0660 && code <= 0x0669) return String(code - 0x0660);
    return ch;
  });
}

/** Normalize to 09XXXXXXXXX (matches API PhoneNormalizer). */
export function normalizeIranMobile(phone: string): string {
  let digits = toAsciiDigits(phone).replace(/\D/g, "");
  if (digits.startsWith("98") && digits.length === 12) digits = `0${digits.slice(2)}`;
  if (digits.length === 10 && digits.startsWith("9")) digits = `0${digits}`;
  return digits;
}

/** Iranian mobile: 09XXXXXXXXX */
export function isValidIranMobile(phone: string): boolean {
  const n = normalizeIranMobile(phone);
  return n.length === 11 && /^09\d{9}$/.test(n);
}

export function iranMobileForApi(phone: string): string | undefined {
  const normalized = normalizeIranMobile(phone.trim());
  return isValidIranMobile(normalized) ? normalized : undefined;
}
