export type Boot = {
	cssUrl: string;
	locale: string;
	siteUrl: string;
};

const DEFAULT_LOCALE = 'en-US';
const BOOT_GLOBAL_NAME = 'linkCheckupBoot';

function readText(
	bootData: Record< string, unknown >,
	key: keyof Boot,
	fallback: string
): string {
	const text = bootData[ key ];

	if ( typeof text !== 'string' ) {
		return fallback;
	}

	return text;
}

export function readBoot( bootData: unknown, origin: string ): Boot {
	const defaults: Boot = {
		cssUrl: '',
		locale: DEFAULT_LOCALE,
		siteUrl: `${ origin }/`,
	};

	if ( typeof bootData !== 'object' || bootData === null ) {
		return defaults;
	}

	const fields = bootData as Record< string, unknown >;

	return {
		cssUrl: readText( fields, 'cssUrl', defaults.cssUrl ),
		locale: readText( fields, 'locale', defaults.locale ),
		siteUrl: readText( fields, 'siteUrl', defaults.siteUrl ),
	};
}

export const boot: Boot = readBoot(
	Reflect.get( window, BOOT_GLOBAL_NAME ),
	window.location.origin
);
