import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';

/// Locale 状态 Notifier
class LocaleNotifier extends StateNotifier<Locale> {
  static const String _key = 'app_locale';

  LocaleNotifier() : super(const Locale('zh', 'CN')) {
    _loadLocale();
  }

  /// 从本地存储加载语言设置
  Future<void> _loadLocale() async {
    final prefs = await SharedPreferences.getInstance();
    final localeCode = prefs.getString(_key);
    if (localeCode != null) {
      state = Locale(localeCode, localeCode == 'zh' ? 'CN' : 'US');
    }
  }

  /// 切换语言
  Future<void> setLocale(Locale locale) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_key, locale.languageCode);
    state = locale;
  }

  /// 切换为中文
  Future<void> setChinese() async {
    await setLocale(const Locale('zh', 'CN'));
  }

  /// 切换为英文
  Future<void> setEnglish() async {
    await setLocale(const Locale('en', 'US'));
  }
}

/// Locale Provider
final localeProvider = StateNotifierProvider<LocaleNotifier, Locale>((ref) {
  return LocaleNotifier();
});

/// 当前语言是否为中文
final isChineseProvider = Provider<bool>((ref) {
  return ref.watch(localeProvider).languageCode == 'zh';
});