import { writable, get } from 'svelte/store';
import { playNewPinChime } from '$lib/utils/sound.js';

export const messagesStore = writable([]); // the store will fill up when the page lloads and queries firestore

// --- "pins pop into existence" live-arrival tracking -----------------------
// Holds the message IDs of pins that just arrived via the real-time listener
// (subscribeToNearbyMessages, messages.js) WHILE the user is actively viewing
// the map - as opposed to pins from the initial getNearbyMessages load/refresh
// (handled by setMessages below, which plays the softer ambient chime
// instead). MapView's renderPins checks this set: any message id in it gets
// the "pop" bounce animation instead of appearing instantly, then clears the
// set so the same pin doesn't re-bounce on the next render.
export const livePinIdsStore = writable(new Set());

// Replaces the store's contents with a fresh list of nearby messages, and
// plays a soft chime if any pin in the new list wasn't present before -
// covering both "someone else posted nearby" and "this device's own query
// refreshed with new results".
export function setMessages(newMessages) {
	const previous = get(messagesStore);
	const previousIds = new Set(previous.map((m) => m.id));
	const hasNewPin = newMessages.some((m) => !previousIds.has(m.id));

	// skip the chime on the very first load (previous list is empty) -
	// otherwise every pin from the initial fetch would "ding" at once
	if (hasNewPin && previous.length > 0) {
		playNewPinChime();
	}

	messagesStore.set(newMessages);
}