/**
 * Generate a UUID v4 string.
 *
 * Uses `window.crypto.getRandomValues()` when available (secure context),
 * falls back to `Math.random()` for non-secure contexts (e.g. plain HTTP).
 *
 * Safe for all environments — does NOT rely on `crypto.randomUUID()`
 * which requires a secure context (HTTPS).
 */
export function generateUUID(): string {
	const array = new Uint8Array(16);
	if (typeof window !== 'undefined' && window.crypto?.getRandomValues) {
		window.crypto.getRandomValues(array);
	} else {
		for (let i = 0; i < 16; i++) array[i] = Math.floor(Math.random() * 256);
	}
	// UUID v4 marker and variant
	array[6] = (array[6] & 0x0f) | 0x40;
	array[8] = (array[8] & 0x3f) | 0x80;
	return [...array]
		.map((b, i) => {
			const hex = b.toString(16).padStart(2, '0');
			if (i === 4 || i === 6 || i === 8 || i === 10) return '-' + hex;
			return hex;
		})
		.join('');
}
