/* eslint-disable no-undef */
/**
 * Image Utilities for PDF Generation
 *
 * Converts image URLs to base64 data URLs for use with pdfmake.
 * pdfmake requires images in base64 format for client-side PDF generation.
 *
 * @see https://pdfmake.github.io/docs/0.1/document-definition-object/images/
 */

/**
 * Convert an image URL to a base64 data URL
 *
 * Uses canvas to convert the image, which handles CORS properly
 * for same-origin images.
 *
 * @param url - Image URL (relative or absolute)
 * @returns Promise resolving to base64 data URL
 */
export async function imageUrlToBase64(url: string): Promise<string> {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.crossOrigin = 'anonymous'

    img.onload = () => {
      const canvas = document.createElement('canvas')
      canvas.width = img.naturalWidth
      canvas.height = img.naturalHeight

      const ctx = canvas.getContext('2d')
      if (!ctx) {
        reject(new Error('Failed to get canvas context'))
        return
      }

      ctx.drawImage(img, 0, 0)

      // Get as PNG to preserve transparency
      const dataUrl = canvas.toDataURL('image/png')
      resolve(dataUrl)
    }

    img.onerror = () => {
      reject(new Error(`Failed to load image: ${url}`))
    }

    img.src = url
  })
}

/**
 * Preload multiple images and return a map of URL to base64
 *
 * Useful for preloading all images before PDF generation.
 *
 * @param urls - Array of image URLs to preload
 * @returns Promise resolving to map of URL -> base64 data URL
 */
export async function preloadImages(urls: string[]): Promise<Map<string, string>> {
  const results = new Map<string, string>()

  await Promise.all(
    urls.map(async (url) => {
      try {
        const base64 = await imageUrlToBase64(url)
        results.set(url, base64)
      } catch (error) {
        console.warn(`Failed to preload image: ${url}`, error)
      }
    })
  )

  return results
}
