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();
    final source = switch (languageCode) {
      'ko' => koStrings,
      'en' => enStrings,
      _ => enStrings,
    };
    return _expandFlatTranslations(source);
  }
}

Map<String, dynamic> _expandFlatTranslations(Map<String, String> flatMap) {
  final nested = <String, dynamic>{};
  for (final entry in flatMap.entries) {
    final key = entry.key;
    if (key.isEmpty) {
      continue;
    }
    final segments = key.split('.');
    Map<String, dynamic> cursor = nested;
    for (var index = 0; index < segments.length; index++) {
      final segment = segments[index];
      if (segment.isEmpty) {
        continue;
      }
      final isLeaf = index == segments.length - 1;
      if (isLeaf) {
        cursor[segment] = _normalizeLocalizationValue(entry.value);
        continue;
      }
      final next = cursor.putIfAbsent(segment, () => <String, dynamic>{});
      if (next is Map<String, dynamic>) {
        cursor = next;
        continue;
      }
      final replacement = <String, dynamic>{};
      cursor[segment] = replacement;
      cursor = replacement;
    }
  }
  return nested;
}

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');
}
