class CurrencyFormatter {
  static const _symbols = {
    'TRY': '₺',
    'USD': '\$',
    'EUR': '€',
    'GBP': '£',
    'AED': 'د.إ',
  };

  static const _rtlSymbols = {'AED'};

  static String symbol(String code) => _symbols[code] ?? code;

  static String format(double amount, String currencyCode) {
    final sym = symbol(currencyCode);
    final isRtl = _rtlSymbols.contains(currencyCode);
    final value = _formatNumber(amount);
    return isRtl ? '$value $sym' : '$sym$value';
  }

  static String _formatNumber(double amount) {
    final formatted = amount.toStringAsFixed(2);
    final parts = formatted.split('.');
    final intPart = parts[0];
    final decPart = parts[1];
    final buf = StringBuffer();
    final digits = intPart.replaceAll('-', '');
    final isNeg = intPart.startsWith('-');
    for (int i = 0; i < digits.length; i++) {
      if (i > 0 && (digits.length - i) % 3 == 0) buf.write(',');
      buf.write(digits[i]);
    }
    return '${isNeg ? '-' : ''}$buf.$decPart';
  }
}
