import { DOWNLOAD_ITEM_IDS } from './constants'
import { downloadDOMToPNG } from './exports'
import { PNGIcon } from './icons'
import type { DownloadItem } from './types'

export interface BuildPngDownloadItemArgs {
  /** Base filename (without extension). The item appends `.png`. */
  filename: string
  /**
   * Reads the capture element to rasterise. Called at click time so the
   * download config doesn't capture a stale reference. Wire it to
   * `() => getCaptureEl(id)` from `widgets-v2/stores`.
   */
  getCaptureEl: () => HTMLElement | null
  /** html2canvas `scale`. Default 2. */
  pixelRatio?: number
  /** html2canvas `backgroundColor`. Default transparent (`null`). */
  backgroundColor?: string | null
  /** Override the menu label. Default `'PNG'`. */
  label?: string
}

/**
 * Builds the standard PNG `DownloadItem` used by every per-widget download
 * config. Centralised so the menu label, icon, error message, and filename
 * suffix stay consistent across widgets without each `create*DownloadConfig`
 * re-deriving the same shape.
 */
export function buildPngDownloadItem(
  args: BuildPngDownloadItemArgs,
): DownloadItem {
  return {
    id: DOWNLOAD_ITEM_IDS.png,
    label: args.label ?? 'PNG',
    icon: <PNGIcon fontSize='small' />,
    resolve: async () => {
      const el = args.getCaptureEl()
      if (!el) {
        throw new Error('[widgets-v2] No PNG capture element available')
      }
      const handle = await downloadDOMToPNG({
        element: el,
        pixelRatio: args.pixelRatio,
        backgroundColor: args.backgroundColor,
      })
      return {
        url: handle.url,
        filename: `${args.filename}.png`,
        revoke: handle.revoke,
      }
    },
  }
}
