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

/**
 * 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 };
}
