/**
 * The boot payload, read once.
 *
 * Everything the shell needs on first paint is localised by PHP, so the app
 * renders before any round trip. Reading it through a function rather than
 * exporting the object directly keeps the failure legible: a missing global
 * means the script was enqueued without wp_localize_script, and that should say
 * so rather than surfacing as `undefined.nonce` three modules away.
 */

import type { Boot } from './types';

declare global {
	interface Window {
		razorbookingBoot?: Boot;
	}
}

let cached: Boot | null = null;

export function boot(): Boot {
	if ( cached ) {
		return cached;
	}

	const payload = window.razorbookingBoot;

	if ( ! payload || ! payload.root ) {
		throw new Error(
			'razorbookingBoot is missing. The admin script was enqueued without its localised data.'
		);
	}

	cached = payload;

	return payload;
}

/** A URL into the RazorBooking admin, for every "configure this over there" link. */
export function appUrl( path = '' ): string {
	const base = boot().appUrl.replace( /\/+$/, '' );

	return path ? `${ base }/${ path.replace( /^\/+/, '' ) }` : base;
}
