export const resizeImage = (file: File, maxWidth = 200): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = (event) => {
      const img = new Image();
      img.src = event.target?.result as string;
      img.onload = () => {
        const canvas = document.createElement('canvas');
        const scale = Math.min(maxWidth / img.width, maxWidth / img.height);

        // Only resize if the image is larger than maxWidth
        const finalWidth = scale < 1 ? img.width * scale : img.width;
        const finalHeight = scale < 1 ? img.height * scale : img.height;

        // Make it a square crop
        const size = Math.min(finalWidth, finalHeight);
        canvas.width = size;
        canvas.height = size;

        const ctx = canvas.getContext('2d');
        if (!ctx) {
          reject(new Error('Failed to get canvas context'));
          return;
        }

        // Calculate crop position to center the image
        const offsetX = (finalWidth - size) / 2;
        const offsetY = (finalHeight - size) / 2;

        // Draw image onto canvas (resizing and cropping it)
        ctx.drawImage(
          img,
          offsetX / scale, offsetY / scale, size / scale, size / scale, // Source coordinates
          0, 0, size, size // Destination coordinates
        );

        // Compress to JPEG with 80% quality
        resolve(canvas.toDataURL('image/jpeg', 0.8));
      };
      img.onerror = (error) => reject(error);
    };
    reader.onerror = (error) => reject(error);
  });
};
