const RASTER_IMAGE_TYPES = new Set(["image/png", "image/jpeg", "image/webp"]);

export async function optimizeBrandingUpload(file: File, kind: "logo" | "background"): Promise<File> {
  if (!RASTER_IMAGE_TYPES.has(file.type)) return file;
  const maxWidth = kind === "logo" ? 640 : 1920;
  const maxHeight = kind === "logo" ? 640 : 1200;
  const quality = kind === "logo" ? 0.84 : 0.8;

  try {
    const bitmap = await createImageBitmap(file);
    const scale = Math.min(1, maxWidth / bitmap.width, maxHeight / bitmap.height);
    const width = Math.max(1, Math.round(bitmap.width * scale));
    const height = Math.max(1, Math.round(bitmap.height * scale));
    const canvas = document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;
    const context = canvas.getContext("2d", { alpha: true });
    if (!context) return file;
    context.drawImage(bitmap, 0, 0, width, height);
    bitmap.close();
    const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, "image/webp", quality));
    if (!blob || blob.size >= file.size) return file;
    return new File([blob], file.name.replace(/\.[^.]+$/, "") + ".webp", { type: "image/webp", lastModified: file.lastModified });
  } catch {
    return file;
  }
}
