puzzle-trainer/lib/session.ts
2026-05-23 01:05:21 +00:00

43 lines
1.5 KiB
TypeScript

import { GAMES, GameId } from "@/lib/levels";
export type PlayMode = "free" | "session";
export function getPlayMode(): PlayMode {
if (typeof window === "undefined") return "free";
return (localStorage.getItem("pt-mode") as PlayMode) ?? "free";
}
export function savePlayMode(mode: PlayMode) {
localStorage.setItem("pt-mode", mode);
}
/**
* Session order for a given date: rotates the starting game each day.
* Day 0 → Q T Z S P, Day 1 → T Z S P Q, etc.
*/
export function getSessionOrder(date: string): GameId[] {
const [y, m, d] = date.split("-").map(Number);
const dayNum = Math.floor(Date.UTC(y, m - 1, d) / 86400000);
const start = dayNum % GAMES.length;
return [...GAMES.slice(start), ...GAMES.slice(0, start)];
}
/** Returns the next unsolved game in the session order, or null if all done / not in session mode. */
export function getNextSessionGame(currentGame: string, date: string): GameId | null {
if (typeof window === "undefined") return null;
if (getPlayMode() !== "session") return null;
const order = getSessionOrder(date);
const currentIdx = order.indexOf(currentGame as GameId);
if (currentIdx === -1) return null;
for (let i = currentIdx + 1; i < order.length; i++) {
const g = order[i];
try {
const raw = localStorage.getItem(`stats-${g}`);
const lastDate = raw ? JSON.parse(raw)?.lastDate : null;
if (lastDate !== date) return g; // not yet solved today
} catch { return g; }
}
return null; // all remaining games solved
}