'use client'
// tdd-guard:skip — browser-only Image/canvas rasterisation, no node-testable logic.

import { getHostOrg } from './host'

/**
 * Logo helpers for the agenda exporters.
 *
 * jspdf's `addImage` needs raster (PNG/JPEG); the host logo + supplier logos
 * may be SVG. This rasterises any same-origin image URL to a PNG data URL via
 * an offscreen canvas. Returns `null` on any failure so exports stay
 * logo-tolerant. The host logo URL is operator-configured (see lib/agenda/host).
 */

export async function rasterizeToPng(
  url: string,
  maxWidth = 240,
  maxHeight = 96,
): Promise<string | null> {
  if (typeof window === 'undefined' || typeof document === 'undefined') return null
  try {
    const response = await fetch(url)
    if (!response.ok) return null
    const blob = await response.blob()
    const objectUrl = URL.createObjectURL(blob)

    const image = new Image()
    image.crossOrigin = 'anonymous'
    const loaded = new Promise<void>((resolve, reject) => {
      image.onload = () => resolve()
      image.onerror = () => reject(new Error('image load failed'))
    })
    image.src = objectUrl
    await loaded

    const intrinsicWidth = image.width || maxWidth
    const intrinsicHeight = image.height || maxHeight
    const ratio = Math.min(maxWidth / intrinsicWidth, maxHeight / intrinsicHeight) || 1
    const scale = (window.devicePixelRatio || 1) > 1 ? 2 : 1
    const drawWidth = intrinsicWidth * ratio
    const drawHeight = intrinsicHeight * ratio

    const canvas = document.createElement('canvas')
    canvas.width = Math.round(drawWidth * scale)
    canvas.height = Math.round(drawHeight * scale)
    const context = canvas.getContext('2d')
    if (!context) {
      URL.revokeObjectURL(objectUrl)
      return null
    }
    context.drawImage(image, 0, 0, canvas.width, canvas.height)
    URL.revokeObjectURL(objectUrl)
    return canvas.toDataURL('image/png')
  } catch {
    return null
  }
}

/** Rasterise the operator-configured host logo, or `null` when none is set. */
export function loadHostLogoPng(): Promise<string | null> {
  const { logoUrl } = getHostOrg()
  if (!logoUrl) return Promise.resolve(null)
  return rasterizeToPng(logoUrl)
}

/**
 * Resolve up to two supplier logos (public URLs / signed storage URLs) to PNG
 * data URLs, dropping any that fail to load.
 */
export async function loadSupplierLogoPngs(urls: string[]): Promise<string[]> {
  const results = await Promise.all(urls.slice(0, 2).map((url) => rasterizeToPng(url)))
  return results.filter((value): value is string => value !== null)
}
