/**
 * Referencia a la implementación NATIVA de crypto.randomUUID, capturada al cargar
 * el módulo (antes de que bootstrap.tsx instale el polyfill). Evita que el polyfill
 * se llame a sí mismo recursivamente.
 */
const nativeRandomUUID: (() => string) | null =
  typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
    ? crypto.randomUUID.bind(crypto)
    : null;

/**
 * Genera un UUID v4 SIN usar crypto.randomUUID (válido en HTTP y HTTPS).
 * Es la función que se instala como polyfill.
 */
export function generateUuidFallback(): string {
  if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {
    const bytes = crypto.getRandomValues(new Uint8Array(16));
    bytes[6] = (bytes[6] & 0x0f) | 0x40;
    bytes[8] = (bytes[8] & 0x3f) | 0x80;
    const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0'));

    return `${hex.slice(0, 4).join('')}-${hex.slice(4, 6).join('')}-${hex.slice(6, 8).join('')}-${hex.slice(8, 10).join('')}-${hex.slice(10, 16).join('')}`;
  }

  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    const r = (Math.random() * 16) | 0;
    const v = c === 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

/**
 * Genera un UUID v4 compatible con contextos seguros (HTTPS/localhost) y no seguros (HTTP).
 */
export function generateUuid(): string {
  return nativeRandomUUID ? nativeRandomUUID() : generateUuidFallback();
}
