import { DEFAULT_MUSIC_VOLUME, DEFAULT_PLATFORM_THEME, type PlatformTheme, type RuntimeSettings, } from '../../packages/shared/src/contracts/runtime'; import {isRecord, readStoredJson, writeStoredJson} from './storage'; const SETTINGS_STORAGE_KEY = 'tavernrealms.settings.v1'; const SETTINGS_STORAGE_VERSION = 1; export type SavedGameSettings = RuntimeSettings; export { DEFAULT_MUSIC_VOLUME }; type StoredGameSettings = SavedGameSettings & { version: number; }; export function clampVolume(value: number) { if (!Number.isFinite(value)) { return DEFAULT_MUSIC_VOLUME; } return Math.max(0, Math.min(1, value)); } export function normalizePlatformTheme(value: unknown): PlatformTheme { return value === 'dark' ? 'dark' : DEFAULT_PLATFORM_THEME; } function parseSavedSettings(value: unknown): SavedGameSettings | null { if (!isRecord(value)) { return null; } if (value.version === SETTINGS_STORAGE_VERSION && typeof value.musicVolume === 'number') { return { musicVolume: clampVolume(value.musicVolume), platformTheme: normalizePlatformTheme(value.platformTheme), }; } if (typeof value.musicVolume === 'number') { return { musicVolume: clampVolume(value.musicVolume), platformTheme: normalizePlatformTheme(value.platformTheme), }; } return null; } export function readSavedSettings() { return ( readStoredJson({ key: SETTINGS_STORAGE_KEY, parse: parseSavedSettings, }) ?? { musicVolume: DEFAULT_MUSIC_VOLUME, platformTheme: DEFAULT_PLATFORM_THEME, } ); } export function writeSavedSettings(settings: SavedGameSettings) { const payload: StoredGameSettings = { version: SETTINGS_STORAGE_VERSION, musicVolume: clampVolume(settings.musicVolume), platformTheme: normalizePlatformTheme(settings.platformTheme), }; return writeStoredJson({ key: SETTINGS_STORAGE_KEY, value: payload, }); }