export const PH_COUNTRY_CODE = '+63';

/** Strip to local mobile digits only (9XXXXXXXXX, max 10). */
export function sanitizeLocalPhoneInput(value: string): string {
  let digits = value.replace(/\D/g, '');

  if (digits.startsWith('63')) {
    digits = digits.slice(2);
  }
  if (digits.startsWith('0')) {
    digits = digits.slice(1);
  }

  return digits.slice(0, 10);
}

/** Convert local digits to E.164 (+639XXXXXXXXX) for API storage. */
export function normalizePhilippinePhone(local: string): string {
  const digits = sanitizeLocalPhoneInput(local);
  if (!digits) return '';
  return `${PH_COUNTRY_CODE}${digits}`;
}

/** Validate Philippine mobile: 10 digits starting with 9. */
export function isValidPhilippineLocalPhone(local: string): boolean {
  return /^9\d{9}$/.test(sanitizeLocalPhoneInput(local));
}

/** Extract local digits from a stored +63 number. */
export function toLocalPhoneNumber(phone?: string | null): string {
  if (!phone) return '';
  return sanitizeLocalPhoneInput(phone.replace(/^\+63/, ''));
}

/** Display as +63 9XX XXX XXXX */
export function formatPhilippinePhoneDisplay(phone: string): string {
  const local = toLocalPhoneNumber(phone);
  if (!local) return '';

  const parts = [local.slice(0, 3), local.slice(3, 6), local.slice(6)].filter(Boolean);
  return `${PH_COUNTRY_CODE} ${parts.join(' ')}`.trim();
}
