/**
 * Sync status store — tracks whether the browser is online and whether there
 * are pending mutations in the offline queue.
 *
 * States:
 *   - 'offline': navigator.onLine is false
 *   - 'syncing': online + queue has > 0 pending ops (being flushed)
 *   - 'synced': online + queue is empty
 *
 * Subscribes to window online/offline events on first read. Safe on SSR
 * (returns 'synced' by default when there's no window).
 */
import { readable, writable, derived, type Readable } from 'svelte/store';
import { browser } from '$app/environment';

export type SyncState = 'synced' | 'syncing' | 'offline';

/** Reactive navigator.onLine value. */
export const isOnline = readable<boolean>(browser ? navigator.onLine : true, (set) => {
	if (!browser) return;
	const update = () => set(navigator.onLine);
	window.addEventListener('online', update);
	window.addEventListener('offline', update);
	return () => {
		window.removeEventListener('online', update);
		window.removeEventListener('offline', update);
	};
});

/** Number of pending ops in the offline queue (set by sync/queue integration). */
export const pendingOpsCount = writable<number>(0);

/** High-level status used by the UI banner. */
export const syncStatus: Readable<SyncState> = derived(
	[isOnline, pendingOpsCount],
	([$online, $pending]) => {
		if (!$online) return 'offline';
		if ($pending > 0) return 'syncing';
		return 'synced';
	}
);
