/**
 * Phone number validation and formatting utilities
 */

/**
 * Validates phone number
 * Phone number must be between 7-15 digits
 * 
 * @param phoneNumber - Phone number to validate
 * @returns true if valid, false otherwise
 */
export const validatePhoneNumber = (phoneNumber: string): boolean => {
  if (!phoneNumber || !phoneNumber.trim()) {
    return false;
  }

  // Extract only digits
  const digitsOnly = phoneNumber.replace(/\D/g, "");
  
  // Check if digits count is between 7-15
  return digitsOnly.length >= 7 && digitsOnly.length <= 15;
};

/**
 * Sanitizes phone number input
 * Allows + at start and digits only, up to 15 digits
 * 
 * @param value - Input value to sanitize
 * @returns Sanitized phone number string
 */
export const sanitizePhoneInput = (value: string): string => {
  if (!value) return "";
  
  // If starts with +, allow + and digits after it
  if (value.startsWith("+")) {
    const afterPlus = value.slice(1).replace(/\D/g, "");
    // Maximum 15 digits after +
    return "+" + afterPlus.slice(0, 15);
  }
  
  // No +, allow only digits, max 15
  return value.replace(/\D/g, "").slice(0, 15);
};

/**
 * Checks if a key should be allowed in phone number input
 * Allows: + at position 0, digits, navigation keys, and control keys
 * 
 * @param key - Keyboard key
 * @param keyCode - Keyboard key code
 * @param ctrlKey - Whether Ctrl key is pressed
 * @param currentValue - Current input value
 * @param cursorPosition - Current cursor position
 * @returns true if key should be allowed
 */
export const isAllowedPhoneKey = (
  key: string,
  keyCode: number,
  ctrlKey: boolean,
  currentValue: string,
  cursorPosition: number
): boolean => {
  // Allow navigation and control keys
  if (
    [8, 9, 27, 13, 46, 35, 36, 37, 39].indexOf(keyCode) !== -1 ||
    // Allow: Ctrl+A, Ctrl+C, Ctrl+V, Ctrl+X
    (keyCode === 65 && ctrlKey) ||
    (keyCode === 67 && ctrlKey) ||
    (keyCode === 86 && ctrlKey) ||
    (keyCode === 88 && ctrlKey)
  ) {
    return true;
  }
  
  // Allow + only at the start (position 0)
  if (key === "+" && cursorPosition === 0 && !currentValue.startsWith("+")) {
    return true;
  }
  
  // Allow digits
  if (
    (keyCode >= 48 && keyCode <= 57) ||
    (keyCode >= 96 && keyCode <= 105)
  ) {
    return true;
  }
  
  return false;
};

