/**
 * Room history — localStorage-backed list of recently visited map rooms.
 */

export interface RoomHistoryEntry {
	slug: string;
	name: string;
	lastVisited: string;
	thumbnail?: string;
	center?: [number, number]; // [lng, lat]
	zoom?: number;
}

const STORAGE_KEY = "rmaps_room_history";
const MAX_ENTRIES = 20;

export function loadRoomHistory(): RoomHistoryEntry[] {
	try {
		const raw = localStorage.getItem(STORAGE_KEY);
		if (raw) return JSON.parse(raw) as RoomHistoryEntry[];
	} catch {}
	return [];
}

function save(entries: RoomHistoryEntry[]): void {
	try {
		localStorage.setItem(STORAGE_KEY, JSON.stringify(entries.slice(0, MAX_ENTRIES)));
	} catch {}
}

export function saveRoomVisit(slug: string, name?: string, center?: [number, number], zoom?: number): void {
	const entries = loadRoomHistory().filter((e) => e.slug !== slug);
	entries.unshift({
		slug,
		name: name || slug,
		lastVisited: new Date().toISOString(),
		center,
		zoom,
	});
	save(entries);
}

export function updateRoomThumbnail(slug: string, thumbnail: string): void {
	const entries = loadRoomHistory();
	const entry = entries.find((e) => e.slug === slug);
	if (entry) {
		entry.thumbnail = thumbnail;
		save(entries);
	}
}

export function removeRoomFromHistory(slug: string): void {
	save(loadRoomHistory().filter((e) => e.slug !== slug));
}
