
/**
 * Detects the orientation of an image from a URL.
 * @param {string} imageUrl - The URL of the image.
 * @returns {Promise<'portrait' | 'landscape' | 'square' | 'unknown'>}
 */
export const detectImageOrientation = (imageUrl) => {
  return new Promise((resolve) => {
    const img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = () => {
      if (img.naturalWidth > img.naturalHeight) resolve('landscape');
      else if (img.naturalHeight > img.naturalWidth) resolve('portrait');
      else resolve('square');
    };
    img.onerror = () => resolve('unknown');
    img.src = imageUrl;
  });
};

/**
 * Calculates optimal crop dimensions for center-cropping an image to fit a target container.
 * Focuses on maintaining aspect ratio without distortion.
 * @param {number} imageWidth - Natural width of the image.
 * @param {number} imageHeight - Natural height of the image.
 * @param {number} containerWidth - Width of the target container (or aspect ratio numerator).
 * @param {number} containerHeight - Height of the target container (or aspect ratio denominator).
 * @returns {{sx: number, sy: number, sWidth: number, sHeight: number}} Crop parameters for drawImage.
 */
export const getCropDimensions = (imageWidth, imageHeight, containerWidth, containerHeight) => {
  const imageRatio = imageWidth / imageHeight;
  const targetRatio = containerWidth / containerHeight;

  let sx, sy, sWidth, sHeight;

  if (imageRatio > targetRatio) {
    // Image is wider than target. Crop sides (center horizontally).
    sHeight = imageHeight;
    sWidth = imageHeight * targetRatio;
    sy = 0;
    sx = (imageWidth - sWidth) / 2;
  } else {
    // Image is taller than target. Crop top/bottom (center vertically).
    sWidth = imageWidth;
    sHeight = imageWidth / targetRatio;
    sx = 0;
    sy = (imageHeight - sHeight) / 2;
  }

  return { sx, sy, sWidth, sHeight };
};

/**
 * Applies a smart center crop to an image using a canvas and returns the cropped image as a data URL.
 * Prevents stretching by calculating exact dimensions.
 * @param {string} imageUrl - The source image URL or data URL.
 * @param {number} [aspectRatio=1.333] - Target aspect ratio (width/height). Default is 4:3.
 * @param {number} [targetWidth=1200] - Base width for resolution.
 * @returns {Promise<string|null>} Data URL of the cropped image.
 */
export const applyCropToCanvas = (imageUrl, aspectRatio = 4/3, targetWidth = 1200) => {
  return new Promise((resolve) => {
    const img = new Image();
    img.crossOrigin = 'Anonymous';
    
    img.onload = () => {
      try {
        const targetHeight = targetWidth / aspectRatio;
        
        const { sx, sy, sWidth, sHeight } = getCropDimensions(
            img.naturalWidth, 
            img.naturalHeight, 
            targetWidth, 
            targetHeight
        );

        const canvas = document.createElement('canvas');
        canvas.width = targetWidth;
        canvas.height = targetHeight;
        
        const ctx = canvas.getContext('2d');
        ctx.imageSmoothingEnabled = true;
        ctx.imageSmoothingQuality = 'high';
        
        // Fill background in case of transparency
        ctx.fillStyle = '#ffffff';
        ctx.fillRect(0, 0, targetWidth, targetHeight);

        // Draw the center-cropped portion onto the canvas
        ctx.drawImage(img, sx, sy, sWidth, sHeight, 0, 0, targetWidth, targetHeight);
        
        // Return high quality JPEG
        resolve(canvas.toDataURL('image/jpeg', 0.92));
      } catch (err) {
        console.error("Error cropping image on canvas", err);
        resolve(null);
      }
    };
    
    img.onerror = () => {
      console.error("Failed to load image for cropping", imageUrl);
      resolve(null);
    };
    
    img.src = imageUrl;
  });
};
