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

const PREFS_KEY = 'classeo_grade_preferences';
const SEEN_KEY = 'classeo_grades_seen';
const REVEALED_KEY = 'classeo_grades_revealed';

export type RevealMode = 'immediate' | 'discover';

interface GradePreferences {
	revealMode: RevealMode;
}

// Reactive state
let revealMode = $state<RevealMode>('immediate');
let seenGradeIds = $state<Set<string>>(new Set());
let revealedGradeIds = $state<Set<string>>(new Set());

// Load from localStorage on init
if (browser) {
	try {
		const stored = localStorage.getItem(PREFS_KEY);
		if (stored) {
			const prefs = JSON.parse(stored) as GradePreferences;
			revealMode = prefs.revealMode ?? 'immediate';
		}
	} catch {
		// Ignore parse errors
	}

	try {
		const stored = localStorage.getItem(SEEN_KEY);
		if (stored) {
			seenGradeIds = new Set(JSON.parse(stored) as string[]);
		}
	} catch {
		// Ignore
	}

	try {
		const stored = localStorage.getItem(REVEALED_KEY);
		if (stored) {
			revealedGradeIds = new Set(JSON.parse(stored) as string[]);
		}
	} catch {
		// Ignore
	}
}

function savePrefs(): void {
	if (!browser) return;
	try {
		localStorage.setItem(PREFS_KEY, JSON.stringify({ revealMode }));
	} catch {
		// QuotaExceededError — preference still active in memory
	}
}

function saveSeen(): void {
	if (!browser) return;
	try {
		localStorage.setItem(SEEN_KEY, JSON.stringify([...seenGradeIds]));
	} catch {
		// QuotaExceededError
	}
}

function saveRevealed(): void {
	if (!browser) return;
	try {
		localStorage.setItem(REVEALED_KEY, JSON.stringify([...revealedGradeIds]));
	} catch {
		// QuotaExceededError
	}
}

export function getRevealMode(): RevealMode {
	return revealMode;
}

export function setRevealMode(mode: RevealMode): void {
	revealMode = mode;
	savePrefs();
}

export function isGradeNew(gradeId: string): boolean {
	return !seenGradeIds.has(gradeId);
}

export function markGradesSeen(gradeIds: string[]): void {
	seenGradeIds = new Set([...seenGradeIds, ...gradeIds]);
	saveSeen();
}

export function isGradeRevealed(gradeId: string): boolean {
	return revealedGradeIds.has(gradeId);
}

export function revealGrade(gradeId: string): void {
	revealedGradeIds = new Set([...revealedGradeIds, gradeId]);
	saveRevealed();
}

export function isDiscoverMode(): boolean {
	return revealMode === 'discover';
}
