/**
 * Utility functions for calculating video aspect ratios and thumbnail dimensions
 */

export const BASE_THUMBNAIL_SIZE = 120;

/**
 * Dimensions for a thumbnail that fits within a square bounding box
 */
export interface ThumbnailDimensions {
  /** Width in pixels */
  width: number;
  /** Height in pixels */
  height: number;
}

/**
 * Calculates thumbnail dimensions that fit within a square bounding box while preserving aspect ratio.
 *
 * The algorithm works by:
 * 1. Fitting the video within a square of `maxDimension` size
 * 2. For landscape videos: width = maxDimension, height = scaled down
 * 3. For portrait videos: height = maxDimension, width = scaled down
 * 4. For invalid dimensions: returns square thumbnails (maxDimension × maxDimension)
 *
 * @param videoWidth - Video width in pixels
 * @param videoHeight - Video height in pixels
 * @param maxDimension - Maximum dimension for thumbnails (defaults to BASE_THUMBNAIL_SIZE)
 * @returns Thumbnail dimensions that fit within the square bounding box
 *
 * @example
 * // 1920×1080 landscape video with 120px max dimension
 * calculateThumbnailDimensions(1920, 1080, 120)
 * // Returns: { width: 120, height: 68 }
 *
 * @example
 * // 1080×1920 portrait video with 120px max dimension
 * calculateThumbnailDimensions(1080, 1920, 120)
 * // Returns: { width: 68, height: 120 }
 *
 * @example
 * // Invalid dimensions fallback to square
 * calculateThumbnailDimensions(0, 0, 120)
 * // Returns: { width: 120, height: 120 }
 */
export function calculateThumbnailDimensions(
  videoWidth: number,
  videoHeight: number,
  maxDimension: number = BASE_THUMBNAIL_SIZE
): ThumbnailDimensions {
  // Validate video dimensions to prevent division by zero
  if (videoWidth <= 0 || videoHeight <= 0) {
    // Fallback to square thumbnails if either dimension is invalid
    return {
      width: maxDimension,
      height: maxDimension,
    };
  }

  const videoAspectRatio = videoWidth / videoHeight;

  if (videoAspectRatio > 1) {
    // Landscape video - use landscape thumbnails
    return {
      width: maxDimension,
      height: Math.round(maxDimension / videoAspectRatio),
    };
  } else {
    // Portrait video - use portrait thumbnails
    return {
      width: Math.round(maxDimension * videoAspectRatio),
      height: maxDimension,
    };
  }
}
