import imageCompression from "browser-image-compression/dist/browser-image-compression.mjs";
import { extname } from "./upload";
const COMPRESSIBLE = new Set([
  "image/jpeg",
  "image/jpg",
  "image/png",
  "image/gif",
  "image/webp",
  "image/bmp"
]);
export function isCompressibleImage(type) {
  if (!type || type.includes("svg"))
    return false;
  return COMPRESSIBLE.has(type);
}
function encodeTypeOf(mime) {
  if (mime === "image/png" || mime === "image/bmp")
    return "image/webp";
  return mime;
}
function renameForType(name, mime) {
  const map = {
    "image/webp": "webp",
    "image/jpeg": "jpg",
    "image/jpg": "jpg",
    "image/png": "png",
    "image/gif": "gif"
  };
  const next = map[mime];
  if (!next)
    return name;
  const cur = extname(name);
  if (!cur)
    return `${name}.${next}`;
  return name.slice(0, -(cur.length + 1)) + `.${next}`;
}
export async function compressImage(file, opts = {}) {
  if (!isCompressibleImage(file.type))
    return file;
  const fileType = encodeTypeOf(file.type);
  try {
    const out = await imageCompression(file, {
      maxSizeMB: 0.05,
      maxWidthOrHeight: undefined,
      useWebWorker: true,
      fileType,
      initialQuality: 0.8,
      alwaysKeepResolution: true,
      onProgress: (p) => {
        opts.onProgress?.(Math.min(100, Math.max(0, Math.round(p))));
      }
    });
    const name = renameForType(file.name, out.type || fileType);
    if (out.name === name)
      return out;
    return new File([out], name, {
      type: out.type || fileType,
      lastModified: Date.now()
    });
  } catch {
    return file;
  }
}
