const SAVE_KEY = 'tyrants-edge-save';
const CURRENT_VERSION = 1;

export class SaveManager {
  static defaultSave() {
    return {
      version: CURRENT_VERSION,
      gold: 400,
      collection: {},
      decks: [],
      campaignProgress: { completedMissions: [], currentChapter: 1 },
      starterDeckReceived: false
    };
  }

  static load() {
    try {
      const raw = localStorage.getItem(SAVE_KEY);
      if (!raw) return SaveManager.defaultSave();
      const data = JSON.parse(raw);
      return SaveManager.migrate(data);
    } catch {
      return SaveManager.defaultSave();
    }
  }

  static save(data) {
    localStorage.setItem(SAVE_KEY, JSON.stringify(data));
  }

  static migrate(data) {
    if (data.version === CURRENT_VERSION) return data;
    // future migrations here
    data.version = CURRENT_VERSION;
    return data;
  }

  static addCard(save, cardId, count = 1) {
    save.collection[cardId] = (save.collection[cardId] || 0) + count;
    SaveManager.save(save);
  }

  static removeCard(save, cardId, count = 1) {
    if (!save.collection[cardId]) return false;
    save.collection[cardId] -= count;
    if (save.collection[cardId] <= 0) delete save.collection[cardId];
    SaveManager.save(save);
    return true;
  }

  static addGold(save, amount) {
    save.gold += amount;
    SaveManager.save(save);
  }

  static spendGold(save, amount) {
    if (save.gold < amount) return false;
    save.gold -= amount;
    SaveManager.save(save);
    return true;
  }

  static completeMission(save, missionId) {
    if (!save.campaignProgress.completedMissions.includes(missionId)) {
      save.campaignProgress.completedMissions.push(missionId);
    }
    SaveManager.save(save);
  }

  static saveDeck(save, deck) {
    const idx = save.decks.findIndex(d => d.id === deck.id);
    if (idx >= 0) save.decks[idx] = deck;
    else save.decks.push(deck);
    SaveManager.save(save);
  }

  static deleteDeck(save, deckId) {
    save.decks = save.decks.filter(d => d.id !== deckId);
    SaveManager.save(save);
  }
}
