import type { GameState } from '../data/types';

const KEY = 'not-tonight-save';

export interface StorageLike {
  getItem(key: string): string | null;
  setItem(key: string, value: string): void;
  removeItem(key: string): void;
}

export function freshGameState(seed: number): GameState {
  return { v: 1, seed, venueIndex: 0, nightIndex: 0, heatStrikes: [], regulars: {}, pastReports: [] };
}

export function saveGame(state: GameState, storage: StorageLike = localStorage): void {
  storage.setItem(KEY, JSON.stringify(state));
}

// Corrupt or version-mismatched saves fall back to a fresh run — never throw.
export function loadGame(fallbackSeed: number, storage: StorageLike = localStorage): GameState {
  try {
    const raw = storage.getItem(KEY);
    if (!raw) return freshGameState(fallbackSeed);
    const parsed: unknown = JSON.parse(raw);
    if (
      typeof parsed === 'object' && parsed !== null &&
      (parsed as GameState).v === 1 &&
      typeof (parsed as GameState).seed === 'number'
    ) {
      return parsed as GameState;
    }
    return freshGameState(fallbackSeed);
  } catch {
    return freshGameState(fallbackSeed);
  }
}

export function clearSave(storage: StorageLike = localStorage): void {
  storage.removeItem(KEY);
}
