import 'package:shared_preferences/shared_preferences.dart';

/// 앱 설정 저장소 (SharedPreferences 기반)
///
/// 언어, 사운드 등 사용자 설정을 로컬에 저장
class SettingsRepository {
  static const _keyLocale = 'locale';
  static const _keyBgmVolume = 'bgm_volume';
  static const _keySfxVolume = 'sfx_volume';
  static const _keyAnimationSpeed = 'animation_speed';

  SharedPreferences? _prefs;

  /// SharedPreferences 초기화
  Future<SharedPreferences> _getPrefs() async {
    _prefs ??= await SharedPreferences.getInstance();
    return _prefs!;
  }

  /// 언어 설정 저장
  Future<void> saveLocale(String locale) async {
    final prefs = await _getPrefs();
    await prefs.setString(_keyLocale, locale);
  }

  /// 언어 설정 불러오기
  Future<String?> loadLocale() async {
    final prefs = await _getPrefs();
    return prefs.getString(_keyLocale);
  }

  /// BGM 볼륨 저장 (0.0 ~ 1.0)
  Future<void> saveBgmVolume(double volume) async {
    final prefs = await _getPrefs();
    await prefs.setDouble(_keyBgmVolume, volume.clamp(0.0, 1.0));
  }

  /// BGM 볼륨 불러오기 (기본값: 0.7)
  Future<double> loadBgmVolume() async {
    final prefs = await _getPrefs();
    return prefs.getDouble(_keyBgmVolume) ?? 0.7;
  }

  /// SFX 볼륨 저장 (0.0 ~ 1.0)
  Future<void> saveSfxVolume(double volume) async {
    final prefs = await _getPrefs();
    await prefs.setDouble(_keySfxVolume, volume.clamp(0.0, 1.0));
  }

  /// SFX 볼륨 불러오기 (기본값: 0.8)
  Future<double> loadSfxVolume() async {
    final prefs = await _getPrefs();
    return prefs.getDouble(_keySfxVolume) ?? 0.8;
  }

  /// 애니메이션 속도 저장 (0.5 ~ 2.0, 1.0이 기본)
  Future<void> saveAnimationSpeed(double speed) async {
    final prefs = await _getPrefs();
    await prefs.setDouble(_keyAnimationSpeed, speed.clamp(0.5, 2.0));
  }

  /// 애니메이션 속도 불러오기 (기본값: 1.0)
  Future<double> loadAnimationSpeed() async {
    final prefs = await _getPrefs();
    return prefs.getDouble(_keyAnimationSpeed) ?? 1.0;
  }
}
