import 'package:flutter/material.dart';

/// 全局语言状态管理
///
/// userLocale = null 时跟随系统语言
/// 用户在设置页选择后，设置为具体 Locale
class LocaleManager {
  static final ValueNotifier<Locale?> userLocale = ValueNotifier(null);

  static const supportedLocales = [
    Locale('zh', 'CN'),
    Locale('zh', 'TW'),
    Locale('en'),
    Locale('ja'),
  ];

  /// 根据系统 locale 解析最佳匹配
  static Locale resolve(List<Locale>? systemLocales, Iterable<Locale> supported) {
    if (systemLocales == null || systemLocales.isEmpty) {
      return const Locale('zh', 'CN');
    }
    final system = systemLocales.first;

    // 精确匹配
    for (final s in supported) {
      if (s.languageCode == system.languageCode &&
          s.countryCode == system.countryCode) {
        return s;
      }
    }

    // 语言码匹配
    for (final s in supported) {
      if (s.languageCode == system.languageCode) {
        return s;
      }
    }

    // 默认中文
    return const Locale('zh', 'CN');
  }

  /// 根据语言获取默认货币
  static String defaultCurrencyForLocale(Locale locale) {
    switch (locale.languageCode) {
      case 'zh':
        return locale.countryCode == 'TW' ? 'TWD' : 'CNY';
      case 'ja':
        return 'JPY';
      case 'en':
      default:
        return 'USD';
    }
  }

  /// Locale 转显示名称
  static String localeDisplayName(Locale locale) {
    final key = '${locale.languageCode}_${locale.countryCode ?? ''}';
    switch (key) {
      case 'zh_CN':
        return '简体中文';
      case 'zh_TW':
        return '繁體中文';
      case 'en_':
      case 'en_US':
        return 'English';
      case 'ja_':
      case 'ja_JP':
        return '日本語';
      default:
        return locale.toString();
    }
  }
}
