/**
 * File transfer adapter — the browser side of Import/Export (spec §08).
 *
 * Per the architecture rule, DOM/file APIs are confined to infrastructure: this
 * is the only module that builds a download or reads a picked file, so the
 * transfer *service* stays about orchestration (normalize, merge, notify) rather
 * than Blobs and anchors.
 */

/**
 * Trigger a download of an already-built object/data `url` as `filename`. A
 * `blob:` URL is revoked right after the click; a `data:` URL needs no cleanup.
 * Used by the per-chart export for an image URL produced by the Vega view
 * (`RenderHandle.toImageURL`).
 */
export function downloadUrl(filename: string, url: string): void {
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  // Firefox needs the anchor in the document for the click to register.
  document.body.appendChild(a);
  a.click();
  a.remove();
  if (url.startsWith('blob:')) URL.revokeObjectURL(url);
}

/** Trigger a client-side download of `json` text as `filename`. */
export function downloadJson(filename: string, json: string): void {
  const url = URL.createObjectURL(new Blob([json], { type: 'application/json' }));
  downloadUrl(filename, url);
}

/** Read a picked file's text content (rejects on an unreadable file). */
export function readTextFile(file: File): Promise<string> {
  return file.text();
}

/** Read a picked file's raw bytes (rejects on an unreadable file) — for font uploads. */
export function readBinaryFile(file: File): Promise<ArrayBuffer> {
  return file.arrayBuffer();
}

/** Copy `text` to the clipboard (rejects when the browser blocks access). The
 *  one place outside a component that touches the clipboard API. */
export function copyText(text: string): Promise<void> {
  return navigator.clipboard.writeText(text);
}
