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

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

  SharedPreferences? _prefs;

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

  /// 테마 모드 저장
  Future<void> saveThemeMode(ThemeMode mode) async {
    await init();
    final value = switch (mode) {
      ThemeMode.light => 'light',
      ThemeMode.dark => 'dark',
      ThemeMode.system => 'system',
    };
    await _prefs!.setString(_keyThemeMode, value);
  }

  /// 테마 모드 불러오기
  Future<ThemeMode> loadThemeMode() async {
    await init();
    final value = _prefs!.getString(_keyThemeMode);
    return switch (value) {
      'light' => ThemeMode.light,
      'dark' => ThemeMode.dark,
      'system' => ThemeMode.system,
      _ => ThemeMode.system, // 기본값
    };
  }

  /// 언어 설정 저장
  Future<void> saveLocale(String locale) async {
    await init();
    await _prefs!.setString(_keyLocale, locale);
  }

  /// 언어 설정 불러오기
  Future<String?> loadLocale() async {
    await init();
    return _prefs!.getString(_keyLocale);
  }

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

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

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

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

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

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