interface RandomUUID {
  (): `${string}-${string}-${string}-${string}-${string}`;
}

let randomUUID: RandomUUID = () => {
  try {
    if (typeof crypto?.randomUUID === 'function') randomUUID = crypto.randomUUID.bind(crypto);
    else {
      randomUUID = () => {
        const temp_url = URL.createObjectURL(new Blob());
        const uuid = temp_url.toString();
        return (URL.revokeObjectURL(temp_url), uuid.split('/').pop()) as ReturnType<typeof randomUUID>;
      };
    }
    return randomUUID();
  } catch (e) {
    randomUUID = () => {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        const r = (Math.random() * 16) | 0;
        const v = c === 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      }) as ReturnType<typeof randomUUID>;
    };
  }
  return randomUUID();
};

export { randomUUID };
