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

import '../../l10n/app_localizations.dart';

/// Persists UI language (English / Telugu) for [AppLocalizations].
class LocaleController extends GetxController {
  static LocaleController get to => Get.find();

  static const String _prefKey = 'app_locale';

  final Rx<Locale> locale = const Locale('en').obs;

  /// Call from [main] after [WidgetsFlutterBinding.ensureInitialized].
  Future<void> ensureLoaded() async {
    final prefs = await SharedPreferences.getInstance();
    final code = prefs.getString(_prefKey);
    if (code == 'te' || code == 'en') {
      locale.value = Locale(code!);
    } else {
      locale.value = const Locale('en');
    }
  }

  Future<void> setLocale(Locale value) async {
    if (value.languageCode != 'en' && value.languageCode != 'te') {
      return;
    }
    locale.value = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefKey, value.languageCode);
    update();
  }

  /// Current choice label for settings subtitle (uses [l10n] for both languages).
  String currentLanguageLabel(AppLocalizations l10n) {
    switch (locale.value.languageCode) {
      case 'te':
        return l10n.languageTelugu;
      case 'en':
      default:
        return l10n.languageEnglish;
    }
  }
}
