/// 格式化工具集
class Formatters {
  Formatters._();

  /// 十六进制字符串转 int
  static int hexToInt(String hex) {
    final clean = hex.startsWith('0x') ? hex.substring(2) : hex;
    return int.parse(clean, radix: 16);
  }

  /// 十六进制字符串转 BigInt
  static BigInt hexToBigInt(String hex) {
    final clean = hex.startsWith('0x') ? hex.substring(2) : hex;
    if (clean.isEmpty) return BigInt.zero;
    return BigInt.parse(clean, radix: 16);
  }

  /// int 转十六进制字符串 (带 0x 前缀)
  static String toHex(int value) {
    return '0x${value.toRadixString(16)}';
  }

  /// BigInt 转十六进制字符串 (带 0x 前缀)
  static String bigIntToHex(BigInt value) {
    return '0x${value.toRadixString(16)}';
  }

  /// BigInt 转 ABI 编码的 uint256（64 字符 hex）
  static String padUint256(BigInt value) {
    return value.toRadixString(16).padLeft(64, '0');
  }

  /// 格式化 GNX 余额 (18 位小数)
  static String formatGnx(BigInt weiValue, {int decimals = 4}) {
    final divisor = BigInt.from(10).pow(18);
    final whole = weiValue ~/ divisor;
    final remainder = weiValue.remainder(divisor);

    final fracStr = remainder.toString().padLeft(18, '0');
    final truncated = fracStr.substring(0, decimals);

    return '$whole.$truncated';
  }

  /// 格式化 Token 余额（自定义精度）
  static String formatToken(BigInt amount, int tokenDecimals,
      {int displayDecimals = 4}) {
    final divisor = BigInt.from(10).pow(tokenDecimals);
    final whole = amount ~/ divisor;
    final remainder = amount.remainder(divisor);

    final fracStr = remainder.toString().padLeft(tokenDecimals, '0');
    final truncated = fracStr.substring(0, displayDecimals);

    return '$whole.$truncated';
  }

  /// 缩短地址显示 (0x1234...abcd)
  static String shortenAddress(String address, {int chars = 4}) {
    if (address.length <= chars * 2 + 2) return address;
    return '${address.substring(0, chars + 2)}...${address.substring(address.length - chars)}';
  }

  /// 缩短交易哈希
  static String shortenTxHash(String hash, {int chars = 8}) {
    return shortenAddress(hash, chars: chars);
  }
}
