/**
 * versionStore - Frontend build version
 *
 * Reads from SvelteKit's `_app/version.json` — generated by the @vite-pwa/sveltekit
 * plugin. The version string changes on every build, so comparing it against
 * localStorage reliably detects server upgrades.
 *
 * In dev mode, falls back to `'dev'`.
 */

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

let version = $state<string>('');

async function loadVersion() {
	if (!browser) return;

	if (import.meta.env.DEV) {
		version = 'dev';
		return;
	}

	try {
		const res = await fetch(`${base}/_app/version.json`, { cache: 'no-store' });
		if (res.ok) {
			const data = await res.json();
			version = data.version ?? '';
		}
	} catch {
		// _app/version.json missing or unreachable - leave as empty string
	}
}

loadVersion();

export const versionStore = {
	get value(): string {
		return version;
	}
};
