// import 'package:get/get.dart';
import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

class GetxTranslations extends Translations {
  final Map<String, Map<String, String>> _translations = {};

  @override
  Map<String, Map<String, String>> get keys => _translations;

  // 初始化并加载所有翻译文件
  Future<void> loadAllTranslations() async {
    _translations['en'] = await _loadTranslations('assets/translations/strings_en.i18n.json');
    _translations['zh_CN'] = await _loadTranslations('assets/translations/strings_zh.i18n.json');
    _translations['zh_TW'] = await _loadTranslations('assets/translations/strings_zh_Hant.i18n.json');
    _translations['es'] =
        await _loadTranslations('assets/translations/strings_es.i18n.json');
    _translations['ja'] =
        await _loadTranslations('assets/translations/strings_ja.i18n.json');
    _translations['ru'] =
        await _loadTranslations('assets/translations/strings_ru.i18n.json');
    _translations['et'] =
        await _loadTranslations('assets/translations/strings_et.i18n.json');
  }

  // 读取并解析 JSON 文件
  Future<Map<String, String>> _loadTranslations(String path) async {
    final Map<String, String> translations = {};
    final String jsonString = await rootBundle.loadString(path);
    final Map<String, dynamic> jsonMap = json.decode(jsonString);
    
    _flattenTranslations(jsonMap, translations);
    
    return translations;
  }

  // 递归提取最底层的翻译文本并展平结构

  void _flattenTranslations(
      Map<String, dynamic> jsonMap, Map<String, String> translations,
      [String prefix = '']) {
    jsonMap.forEach((key, value) {
      final newKey = prefix.isEmpty ? key : '$prefix.$key';
      if (value is Map<String, dynamic>) {
        _flattenTranslations(value, translations, newKey);
      } else if (value is String) {
        // 替换占位符 {xxx} 为 @xxx
        final modifiedValue = value.replaceAllMapped(
          RegExp(r'\{(\w+)\}'),
          (match) => '@${match.group(1)}',
        );
        translations[newKey] = modifiedValue;
      }
    });
  }
}
