/**
 * Toolkit - Phone Number Formatting
 * 
 * Utilities for formatting phone numbers.
 */

/**
 * Format a phone number for display
 * Handles basic international formats
 */
export function formatPhoneNumber(phone: string): string {
  // Remove all non-digit characters
  const digits = phone.replace(/\D/g, "");

  // Handle common formats
  if (digits.length === 10) {
    // US/Canada format: (123) 456-7890
    return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6)}`;
  } else if (digits.length === 11 && digits.startsWith("1")) {
    // US/Canada with country code: +1 (123) 456-7890
    return `+1 (${digits.slice(1, 4)}) ${digits.slice(4, 7)}-${digits.slice(7)}`;
  } else if (digits.length >= 10) {
    // International format: +XX XXX XXX XXXX
    const countryCode = digits.slice(0, digits.length - 10);
    const areaCode = digits.slice(-10, -7);
    const localPrefix = digits.slice(-7, -4);
    const localNumber = digits.slice(-4);
    return `+${countryCode} ${areaCode} ${localPrefix} ${localNumber}`;
  }

  // Return original if no known format matches
  return phone;
}

/**
 * Normalize a phone number to E.164 format (+XXXXXXXXXXX)
 */
export function normalizePhoneNumber(phone: string, defaultCountryCode = "1"): string {
  const digits = phone.replace(/\D/g, "");
  
  // If already has country code, return with +
  if (digits.length >= 10 && !digits.startsWith(defaultCountryCode)) {
    return `+${digits}`;
  }
  
  // Add default country code
  return `+${defaultCountryCode}${digits}`;
}

