const ASPECT_RATIO_PATTERN = /^\d+:\d+$/;

export const DEFAULT_ASPECT_RATIO = "16:9";

const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));

/**
 * Normalize aspect ratio to "width:height" (e.g. "16:9", "4:3").
 * Accepts "16/9" as well as "16:9".
 *
 * @param {string|number} value
 * @returns {string|undefined}
 */
export function normalizeAspectRatio(value) {
  if (value === undefined || value === null || value === "") {
    return undefined;
  }

  const normalized = String(value).trim().replace("/", ":");

  if (!ASPECT_RATIO_PATTERN.test(normalized)) {
    throw new Error(
      'aspectRatio must be in "width:height" format (e.g. "16:9" or "4:3").'
    );
  }

  return normalized;
}

/**
 * @param {string|undefined} aspectRatio
 * @returns {{ width: number, height: number }|null}
 */
export function parseAspectRatio(aspectRatio) {
  if (!aspectRatio) {
    return null;
  }

  const [width, height] = aspectRatio.split(":").map(Number);
  if (!width || !height) {
    return null;
  }

  return { width, height };
}

/**
 * Build a simplified "width:height" ratio from intrinsic video dimensions.
 *
 * @param {number} width
 * @param {number} height
 * @returns {string|undefined}
 */
export function formatAspectRatioFromDimensions(width, height) {
  if (!width || !height) {
    return undefined;
  }

  const divisor = gcd(width, height);
  return `${width / divisor}:${height / divisor}`;
}
