// tdd-guard:skip — DOM-dependent (SVG serialization, Canvas, URL.createObjectURL)
// cannot be unit-tested without a browser environment. CSV-builder (the pure
// piece) is tested separately in __tests__/csv-builder.test.ts.
//
// Exports a Recharts SVG element as PNG or SVG file.
// devicePixelRatio is respected for crisp PNG output on HiDPI displays.

/**
 * Download the SVG element inside `container` as an SVG file.
 * @param container - DOM element that wraps the Recharts `<ResponsiveContainer>`.
 * @param fileName  - base name without extension.
 */
/**
 * Trigger a browser download for a blob URL. Revocation is deferred — revoking
 * synchronously after click() makes Firefox cancel the not-yet-started fetch.
 */
export function triggerBlobDownload(url: string, downloadName: string): void {
  const a = document.createElement('a')
  a.href = url
  a.download = downloadName
  document.body.appendChild(a)
  a.click()
  setTimeout(() => {
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  }, 100)
}

export function downloadSvg(container: HTMLElement, fileName: string): void {
  const svgEl = container.querySelector('svg')
  if (!svgEl) return
  const serializer = new XMLSerializer()
  const svgStr = serializer.serializeToString(svgEl)
  const blob = new Blob([svgStr], { type: 'image/svg+xml;charset=utf-8' })
  triggerBlobDownload(URL.createObjectURL(blob), `${fileName}.svg`)
}

/**
 * Download the SVG element inside `container` as a PNG file.
 * Respects devicePixelRatio for crisp output on HiDPI displays.
 * @param container - DOM element that wraps the Recharts `<ResponsiveContainer>`.
 * @param fileName  - base name without extension.
 */
export async function downloadPng(container: HTMLElement, fileName: string): Promise<void> {
  const svgEl = container.querySelector('svg')
  if (!svgEl) return

  const width = svgEl.clientWidth || 800
  const height = svgEl.clientHeight || 400
  const dpr = typeof window !== 'undefined' ? (window.devicePixelRatio || 1) : 1

  const serializer = new XMLSerializer()
  const svgStr = serializer.serializeToString(svgEl)
  const svgBlob = new Blob([svgStr], { type: 'image/svg+xml;charset=utf-8' })
  const svgUrl = URL.createObjectURL(svgBlob)

  return new Promise((resolve) => {
    const img = new Image()
    img.onload = () => {
      const canvas = document.createElement('canvas')
      canvas.width = width * dpr
      canvas.height = height * dpr
      const ctx = canvas.getContext('2d')
      if (!ctx) { URL.revokeObjectURL(svgUrl); resolve(); return }
      ctx.scale(dpr, dpr)
      ctx.drawImage(img, 0, 0, width, height)
      URL.revokeObjectURL(svgUrl)
      canvas.toBlob((blob) => {
        if (!blob) { resolve(); return }
        triggerBlobDownload(URL.createObjectURL(blob), `${fileName}.png`)
        resolve()
      }, 'image/png')
    }
    img.onerror = () => { URL.revokeObjectURL(svgUrl); resolve() }
    img.src = svgUrl
  })
}
