/**
 * Trigger a browser download for a Blob with the given filename.
 *
 * The naive pattern (`<a download={name}>` synthesized, click()'d, then
 * URL.revokeObjectURL'd) silently drops the `download` attribute on
 * Chromium-based browsers when the anchor isn't attached to the DOM.
 * The browser then names the file after the blob URL (a UUID) with no
 * extension. Appending to body, clicking, removing - in that order -
 * keeps the attribute honoured everywhere.
 *
 * `URL.revokeObjectURL` runs on the next tick so the browser has a
 * chance to read the URL before it's released; revoking synchronously
 * can race with the download start in Safari.
 */
export function triggerBlobDownload(blob: Blob, filename: string): void {
  const url = URL.createObjectURL(blob);
  triggerUrlDownload(url, filename);
  // Defer revoke to next microtask so the navigation can latch the URL.
  queueMicrotask(() => URL.revokeObjectURL(url));
}

/**
 * Trigger a browser download from an already-resolved URL (e.g. a
 * presigned S3 / MinIO URL). Same DOM-attached pattern as
 * triggerBlobDownload - without it Chromium drops the `download`
 * attribute and the file lands with the URL's last path segment as
 * the filename (a UUID, no extension).
 */
export function triggerUrlDownload(url: string, filename: string): void {
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.rel = 'noopener';
  document.body.appendChild(a);
  a.click();
  a.remove();
}
