import 'dart:math';


/// Masks a card number, leaving only the last 4 digits visible.
/// Returns 'N/A' when the input is null or empty.
String? maskCardNumber(String? pan) {
  if (pan == null || pan.isEmpty) return null;

  // Strip non-digits to avoid leaking formatting patterns.
  final digits = pan.replaceAll(RegExp(r'\D'), '');
  if (digits.length <= 4) return digits;

  final last4 = digits.substring(digits.length - 4);
  final maskedPrefix = '*' * (digits.length - 4);
  final masked = '$maskedPrefix$last4';

  // Group into blocks of 4 for readability.
  final groups = <String>[];
  for (var i = 0; i < masked.length; i += 4) {
    final end = min(i + 4, masked.length);
    groups.add(masked.substring(i, end));
  }

  return groups.join(' ');
}

String? maskAccountEdge(String? value, {int head = 2, int tail = 2}) {
  if (value == null) return null;
  final trimmed = value.replaceAll(RegExp(r'\s+'), '');
  if (trimmed.isEmpty) return null;
  if (trimmed.length <= head + tail) return trimmed;
  final start = trimmed.substring(0, head);
  final end = trimmed.substring(trimmed.length - tail);
  return '$start*****$end';
}
