import type { AspectRatioPreset } from "@/lib/trimmer-types";

export function formatFileSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

export function formatTime(seconds: number): string {
  const safe = Math.max(0, seconds);
  const mins = Math.floor(safe / 60);
  const secs = Math.floor(safe % 60);
  return `${String(mins).padStart(2, "0")}:${String(secs).padStart(2, "0")}`;
}

export function getAspectRatioValue(
  preset: AspectRatioPreset
): number | undefined {
  switch (preset) {
    case "16:9":
      return 16 / 9;
    case "9:16":
      return 9 / 16;
    case "1:1":
      return 1;
    case "4:3":
      return 4 / 3;
    default:
      return undefined;
  }
}

export function scaleCropToVideo(
  crop: { x: number; y: number; w: number; h: number },
  display: { width: number; height: number },
  video: { width: number; height: number }
) {
  const scaleX = video.width / display.width;
  const scaleY = video.height / display.height;

  const x = Math.round(crop.x * scaleX);
  const y = Math.round(crop.y * scaleY);
  let w = Math.round(crop.w * scaleX);
  let h = Math.round(crop.h * scaleY);

  w = Math.min(w, video.width - x);
  h = Math.min(h, video.height - y);
  w = w % 2 === 0 ? w : w - 1;
  h = h % 2 === 0 ? h : h - 1;

  return {
    x: Math.max(0, x),
    y: Math.max(0, y),
    w: Math.max(2, w),
    h: Math.max(2, h),
  };
}

export function parseFfmpegProgress(message: string): number | null {
  const match = message.match(/time=(\d+):(\d+):(\d+\.\d+)/);
  if (!match) return null;
  const hours = Number(match[1]);
  const mins = Number(match[2]);
  const secs = Number(match[3]);
  return hours * 3600 + mins * 60 + secs;
}
