import { DAYS } from './game';

/** Best grade per day, in localStorage. The whole save system — nothing else
 *  persists, by design: runs are the game, stamps are the trophy shelf. */
const KEY = 'sandoniette.v1';
const RANK: Record<string, number> = { S: 5, A: 4, B: 3, C: 2, D: 1 };

export interface Progress {
  best: Record<number, string>;
}

export function loadProgress(): Progress {
  try {
    const p = JSON.parse(localStorage.getItem(KEY) ?? '') as Progress;
    return p && typeof p.best === 'object' ? p : { best: {} };
  } catch {
    return { best: {} };
  }
}

/** Keep the better grade. Returns true if this was an improvement. */
export function recordGrade(day: number, grade: string): boolean {
  const p = loadProgress();
  if ((RANK[grade] ?? 0) <= (RANK[p.best[day]] ?? 0)) return false;
  p.best[day] = grade;
  try {
    localStorage.setItem(KEY, JSON.stringify(p));
  } catch {
    /* private-mode etc. — the run still played */
  }
  return true;
}

export function clearedAll(): boolean {
  const p = loadProgress();
  return DAYS.every((_, i) => p.best[i] !== undefined);
}
