/**
 * Profile pictures are no longer compressed on the way out — the client
 * reported visibly soft avatars, and the backend stores the file as it arrives.
 * The crop is written at its native pixel size and encoded at maximum quality.
 *
 * The edge cap is only a crash guard: an unbounded canvas from a modern phone
 * photo (100MP+) can exhaust memory in mobile Safari. At 4096 it is far above
 * anything the UI renders (the largest avatar on screen is 300px), so in
 * practice no realistic photo is resized at all.
 */
const MAX_PROFILE_PICTURE_EDGE = 4096;
const PROFILE_PICTURE_QUALITY = 1;

/** Renders the selected crop region to a full-quality JPEG File. */
export async function createCroppedImage(
  imageSrc: string,
  pixelCrop: { x: number; y: number; width: number; height: number },
  fileName: string
): Promise<File> {
  const image = new window.Image();
  image.src = imageSrc;

  return new Promise((resolve) => {
    image.onload = () => {
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");

      if (!ctx) return;

      // Native crop size, only shrinking if it exceeds the crash guard above
      const scale = Math.min(
        1,
        MAX_PROFILE_PICTURE_EDGE / Math.max(pixelCrop.width, pixelCrop.height)
      );
      canvas.width = Math.round(pixelCrop.width * scale);
      canvas.height = Math.round(pixelCrop.height * scale);

      // Clear the canvas so transparency is handled correctly
      ctx.fillStyle = "white";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.imageSmoothingQuality = "high";

      // Draw the cropped portion into the (possibly smaller) canvas
      ctx.drawImage(
        image,
        pixelCrop.x,
        pixelCrop.y,
        pixelCrop.width,
        pixelCrop.height,
        0,
        0,
        canvas.width,
        canvas.height
      );

      canvas.toBlob(
        (blob) => {
          if (blob) {
            resolve(new File([blob], fileName, { type: "image/jpeg" }));
          }
        },
        "image/jpeg",
        PROFILE_PICTURE_QUALITY
      );
    };
  });
}
