import 'dart:ui';

import 'package:easy_localization/easy_localization.dart';

import '../../i18n_data.dart';

class TomlAssetLoader extends AssetLoader {
  const TomlAssetLoader();

  @override
  Future<Map<String, dynamic>> load(String path, Locale locale) async {
    final languageCode = locale.languageCode.toLowerCase();
    return switch (languageCode) {
      'ko' => _normalizedKoStrings,
      'en' => _normalizedEnStrings,
      _ => _normalizedEnStrings,
    };
  }
}

final Map<String, dynamic> _normalizedKoStrings = _normalizeFlatTranslations(
  koStrings,
);
final Map<String, dynamic> _normalizedEnStrings = _normalizeFlatTranslations(
  enStrings,
);

Map<String, dynamic> _normalizeFlatTranslations(Map<String, String> flatMap) =>
    Map.fromEntries(
      flatMap.entries
          .where((entry) => _isUserfrontTranslationKey(entry.key))
          .map(
            (entry) =>
                MapEntry(entry.key, _normalizeLocalizationValue(entry.value)),
          ),
    );

bool _isUserfrontTranslationKey(String key) {
  return key.startsWith('domain.') ||
      key.startsWith('err.userfront.') ||
      key.startsWith('msg.userfront.') ||
      key.startsWith('ui.userfront.') ||
      key.startsWith('ui.common.');
}

String _normalizeLocalizationValue(String value) {
  return value
      .replaceAllMapped(
        RegExp(r'\{\{\s*([a-zA-Z0-9_]+)\s*\}\}'),
        (match) => '{${match.group(1)}}',
      )
      .replaceAll(r'\\n', '\n')
      .replaceAll(r'\n', '\n');
}
