import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../providers.dart';
import 'config/game_config.dart';

class SaveManager {
  static const String _saveKey = GameConfig.saveKey;

  static Future<void> saveGame(BattleProvider provider) async {
    final prefs = await SharedPreferences.getInstance();

    final saveData = {
      'stage': provider.stage,
      'turnCount': provider.turnCount,
      'player': provider.player.toJson(),
      'timestamp': DateTime.now().toIso8601String(),
    };

    await prefs.setString(_saveKey, jsonEncode(saveData));
  }

  static Future<Map<String, dynamic>?> loadGame() async {
    final prefs = await SharedPreferences.getInstance();
    if (!prefs.containsKey(_saveKey)) return null;

    final jsonStr = prefs.getString(_saveKey);
    if (jsonStr == null) return null;

    try {
      return jsonDecode(jsonStr);
    } catch (e) {
      print("Error loading save data: $e");
      return null;
    }
  }

  static Future<bool> hasSaveData() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.containsKey(_saveKey);
  }

  static Future<void> clearSaveData() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_saveKey);
  }
}
