import { SAVE_KEY } from './config.js';
import { City } from './game/city.js';

/**
 * Save system: autosave slot in localStorage, 3 manual slots,
 * JSON export/import via file download / picker.
 */
export class SaveManager {
  constructor(city) {
    this.city = city;
    this.SLOT_PREFIX = 'polycity.slot.';
  }

  autosave() {
    try {
      localStorage.setItem(SAVE_KEY, JSON.stringify(this.city.toJSON()));
      return true;
    } catch (e) { console.warn('Autosave failed', e); return false; }
  }

  loadAutosave() {
    return this._loadKey(SAVE_KEY);
  }

  saveSlot(n) {
    try {
      localStorage.setItem(this.SLOT_PREFIX + n, JSON.stringify({
        ...this.city.toJSON(),
        savedAt: Date.now()
      }));
      return true;
    } catch (e) { console.warn('Save failed', e); return false; }
  }

  slotInfo(n) {
    const raw = localStorage.getItem(this.SLOT_PREFIX + n);
    if (!raw) return null;
    try {
      const d = JSON.parse(raw);
      return { name: d.name, pop: (d.history && d.history.length ? d.history[d.history.length - 1].pop : 0), savedAt: d.savedAt };
    } catch { return null; }
  }

  loadSlot(n) {
    return this._loadKey(this.SLOT_PREFIX + n);
  }

  deleteSlot(n) { localStorage.removeItem(this.SLOT_PREFIX + n); }

  hasAutosave() { return !!localStorage.getItem(SAVE_KEY); }

  _loadKey(key) {
    const raw = localStorage.getItem(key);
    if (!raw) return null;
    try {
      return City.fromJSON(JSON.parse(raw));
    } catch (e) {
      console.warn('Corrupt save', e);
      return null;
    }
  }

  exportFile() {
    const blob = new Blob([JSON.stringify(this.city.toJSON())], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${this.city.name.replace(/\s+/g, '-').toLowerCase()}-save.json`;
    a.click();
    setTimeout(() => URL.revokeObjectURL(url), 2000);
  }

  importFile(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => {
        try {
          resolve(City.fromJSON(JSON.parse(reader.result)));
        } catch (e) { reject(e); }
      };
      reader.onerror = reject;
      reader.readAsText(file);
    });
  }
}
