import { browser } from '$app/environment';

export interface Preferences {
	NearToMe: boolean;
	ShowPassingTrains: boolean;
	BoardWakeLock: boolean;
	AutoRefresh: boolean;
}

const STORAGE_KEY = 'ob_pref';

const DEFAULT_PREFS: Preferences = {
	NearToMe: false,
	ShowPassingTrains: true,
	BoardWakeLock: true,
	AutoRefresh: true
};

function loadPrefs(): Preferences {
	if (!browser) return DEFAULT_PREFS;
	const stored = localStorage.getItem(STORAGE_KEY);
	if (!stored) return DEFAULT_PREFS;

	try {
		const parsed = JSON.parse(stored);
		const cleaned = {} as Preferences;

		for (const key of Object.keys(DEFAULT_PREFS) as Array<keyof Preferences>) {
			cleaned[key] = key in parsed ? parsed[key] : DEFAULT_PREFS[key];
		}
		return cleaned;
	} catch {
		return DEFAULT_PREFS;
	}
}

class PreferencesStore {
	current = $state<Preferences>(loadPrefs());

	constructor() {
		$effect.root(() => {
			$effect(() => {
				if (browser) {
					localStorage.setItem(STORAGE_KEY, JSON.stringify(this.current));
				}
			});
		});
	}

	toggleNearToMe(enabled: boolean) {
		this.current.NearToMe = enabled;
	}

	toggleShowPassingTrains(enabled: boolean) {
		this.current.ShowPassingTrains = enabled;
	}

	toggleBoardWakeLock(enabled: boolean) {
		this.current.BoardWakeLock = enabled;
	}

	toggleAutoRefresh(enabled: boolean) {
		this.current.AutoRefresh = enabled;
	}
}

export const prefs = new PreferencesStore();
