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

const STORAGE_KEY = 'classeo:homework:status';

interface HomeworkStatusEntry {
	done: boolean;
	doneAt: number | null;
}

type StatusMap = Record<string, HomeworkStatusEntry>;

function loadStatuses(): StatusMap {
	if (!browser) return {};

	try {
		const raw = localStorage.getItem(STORAGE_KEY);
		return raw ? (JSON.parse(raw) as StatusMap) : {};
	} catch {
		return {};
	}
}

function saveStatuses(statuses: StatusMap): void {
	if (!browser) return;
	localStorage.setItem(STORAGE_KEY, JSON.stringify(statuses));
}

let statuses = $state<StatusMap>(loadStatuses());

/**
 * Marque un devoir comme "fait" ou "à faire".
 */
export function toggleHomeworkDone(homeworkId: string): void {
	const current = statuses[homeworkId];
	const isDone = current?.done ?? false;

	statuses = {
		...statuses,
		[homeworkId]: {
			done: !isDone,
			doneAt: !isDone ? Date.now() : null,
		},
	};

	saveStatuses(statuses);
}

/**
 * Vérifie si un devoir est marqué comme "fait".
 */
export function isHomeworkDone(homeworkId: string): boolean {
	return statuses[homeworkId]?.done ?? false;
}

/**
 * Retourne le map complet des statuts (réactif via $state).
 */
export function getHomeworkStatuses(): StatusMap {
	return statuses;
}
