/** نرمال‌سازی شماره موبایل — هم‌منطق torbatkar MinimalLogin */

const PERSIAN = "۰۱۲۳۴۵۶۷۸۹";
const ARABIC = "٠١٢٣٤٥٦٧٨٩";
const LATIN = "0123456789";

export function persianToEnglish(str: string): string {
  if (!str) return "";
  let result = str;
  for (let i = 0; i < PERSIAN.length; i++) {
    result = result.replace(new RegExp(PERSIAN[i], "g"), LATIN[i]);
    result = result.replace(new RegExp(ARABIC[i], "g"), LATIN[i]);
  }
  return result;
}

export function normalizePhone(phone: string): string {
  if (!phone?.trim()) return "";

  let normalized = persianToEnglish(phone)
    .trim()
    .replace(/\s/g, "")
    .replace(/-/g, "")
    .replace(/\D/g, "");

  if (!normalized) return "";

  if (normalized.startsWith("0098")) normalized = normalized.slice(4);
  else if (normalized.startsWith("98")) normalized = normalized.slice(2);

  if (!normalized.startsWith("0")) {
    if (normalized.length > 10) normalized = normalized.slice(-10);
    normalized = "0" + normalized;
  } else if (normalized.length > 11) {
    normalized = normalized.slice(0, 11);
  }

  return normalized;
}

export function isValidMobile(phone: string): boolean {
  return phone.startsWith("09") && phone.length === 11;
}

export function normalizeOtpCode(value: string): string {
  return persianToEnglish(value).replace(/\D/g, "").slice(0, 4);
}
