import type { FitMode } from "./slot-parser.ts"

export type FitResult = {
  x: number
  y: number
  width: number
  height: number
  viewBox: string
}

export function computeFit(
  fit: FitMode,
  slotX: number,
  slotY: number,
  slotW: number,
  slotH: number,
  contentW: number,
  contentH: number,
): FitResult {
  if (fit === "stretch") {
    return {
      x: slotX,
      y: slotY,
      width: slotW,
      height: slotH,
      viewBox: `0 0 ${contentW} ${contentH}`,
    }
  }
  if (fit === "cover") {
    const scale = Math.max(slotW / contentW, slotH / contentH)
    const renderedW = contentW * scale
    const renderedH = contentH * scale
    const offsetX = slotX + (slotW - renderedW) / 2
    const offsetY = slotY + (slotH - renderedH) / 2
    return {
      x: offsetX,
      y: offsetY,
      width: renderedW,
      height: renderedH,
      viewBox: `0 0 ${contentW} ${contentH}`,
    }
  }
  const scale = Math.min(slotW / contentW, slotH / contentH)
  const renderedW = contentW * scale
  const renderedH = contentH * scale
  const offsetX = slotX + (slotW - renderedW) / 2
  const offsetY = slotY + (slotH - renderedH) / 2
  return {
    x: offsetX,
    y: offsetY,
    width: renderedW,
    height: renderedH,
    viewBox: `0 0 ${contentW} ${contentH}`,
  }
}

export function parseViewBox(svg: string): { width: number; height: number } {
  const m = svg.match(/viewBox=["']([^"']+)["']/)
  if (m) {
    const parts = m[1].split(/[\s,]+/).map(Number)
    if (parts.length === 4 && parts.every((n) => !Number.isNaN(n))) {
      return { width: parts[2], height: parts[3] }
    }
  }
  const wMatch = svg.match(/\swidth=["'](\d+)["']/)
  const hMatch = svg.match(/\sheight=["'](\d+)["']/)
  if (wMatch && hMatch) {
    return { width: parseInt(wMatch[1], 10), height: parseInt(hMatch[1], 10) }
  }
  return { width: 24, height: 24 }
}