export type Difficulty = "casual" | "classic" | "pressure";
export type Quality = "low" | "med" | "high";

export interface Settings {
  music: number;
  sfx: number;
  shake: boolean;
  particles: boolean;
  quality: Quality;
  colorblind: boolean;
  reducedMotion: boolean;
  lantern: boolean;
  ghost: boolean;
  difficulty: Difficulty;
}

export interface ScoreRow {
  name: string;
  score: number;
  at: string;
  extra?: string;
}

export interface SaveData {
  settings: Settings;
  seenTutorial: boolean;
  unlocked: number;
  campaignBest: number;
  campaignScore: number;
  levelBest: number[];
  endlessBest: number;
  dailyBest: { date: string; score: number } | null;
  scores: {
    campaign: ScoreRow[];
    endless: ScoreRow[];
    daily: ScoreRow[];
  };
  lastName: string;
}

export const DEFAULT_SETTINGS: Settings = {
  music: 0.7,
  sfx: 0.85,
  shake: true,
  particles: true,
  quality: "high",
  colorblind: false,
  reducedMotion: false,
  lantern: true,
  ghost: true,
  difficulty: "classic",
};

const KEY = "lumina-pipedream-v1";

function empty(): SaveData {
  return {
    settings: { ...DEFAULT_SETTINGS },
    seenTutorial: false,
    unlocked: 1,
    campaignBest: 0,
    campaignScore: 0,
    levelBest: Array(20).fill(0),
    endlessBest: 0,
    dailyBest: null,
    scores: { campaign: [], endless: [], daily: [] },
    lastName: "OPERATOR",
  };
}

export function loadSave(): SaveData {
  try {
    const raw = localStorage.getItem(KEY);
    if (!raw) return empty();
    const p = JSON.parse(raw) as Partial<SaveData>;
    const base = empty();
    return {
      ...base,
      ...p,
      settings: { ...DEFAULT_SETTINGS, ...(p.settings ?? {}) },
      scores: {
        campaign: p.scores?.campaign ?? [],
        endless: p.scores?.endless ?? [],
        daily: p.scores?.daily ?? [],
      },
      levelBest: Array.from({ length: 20 }, (_, i) => p.levelBest?.[i] ?? 0),
    };
  } catch {
    return empty();
  }
}

export function writeSave(data: SaveData): void {
  try {
    localStorage.setItem(KEY, JSON.stringify(data));
  } catch {
    /* sandbox / private mode */
  }
}

export function pushScore(
  list: ScoreRow[],
  row: ScoreRow,
  keep = 10,
): ScoreRow[] {
  return [...list, row].sort((a, b) => b.score - a.score).slice(0, keep);
}

export const DIFF_MULT = {
  casual: { delay: 1.55, speed: 0.68, score: 0.75 },
  classic: { delay: 1, speed: 1, score: 1 },
  pressure: { delay: 0.72, speed: 1.28, score: 1.35 },
} as const;
