/**
 * Client-side re-encode to WebP before upload — smaller files on the wire and in ImageKit,
 * without a server round-trip. Canvas-based (no extra dependency).
 */
export async function toWebP(
  file: File,
  opts: { maxWidth?: number; maxHeight?: number; quality?: number } = {},
): Promise<File> {
  // Canvas flattens animated GIFs to a single frame — leave those alone rather than break them.
  if (file.type === "image/gif") return file;

  const { maxWidth = 1920, maxHeight = 1920, quality = 0.82 } = opts;

  try {
    const bitmap = await createImageBitmap(file);
    const scale = Math.min(1, maxWidth / bitmap.width, maxHeight / bitmap.height);
    const width = Math.round(bitmap.width * scale);
    const height = Math.round(bitmap.height * scale);

    const canvas = document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;
    const ctx = canvas.getContext("2d");
    if (!ctx) return file;
    ctx.drawImage(bitmap, 0, 0, width, height);
    bitmap.close();

    const blob: Blob | null = await new Promise((resolve) =>
      canvas.toBlob(resolve, "image/webp", quality),
    );
    if (!blob) return file;

    const newName = file.name.replace(/\.[^./\\]+$/, "") + ".webp";
    return new File([blob], newName, { type: "image/webp" });
  } catch {
    // Never block an upload on a conversion failure — fall back to the original file.
    return file;
  }
}
