import type { JustifiedInputImage } from "@/actions/portfolio/getJustifiedImages";

export interface JustifiedImage extends JustifiedInputImage {
  width: number;
  height: number;
}

function shuffleImages<T>(arr: T[]): T[] {
  const shuffled = [...arr];
  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
  }
  return shuffled;
}

export function justifyPortfolioImages(
  images: JustifiedInputImage[],
  containerWidth: number,
  rowHeight: number,
  gap: number = 4
): JustifiedImage[][] {
  const shuffledImages = shuffleImages(images);

  const rows: JustifiedImage[][] = [];
  let currentRow: JustifiedInputImage[] = [];
  let currentWidth = 0;

  for (const image of shuffledImages) {
    const scale = rowHeight / image.height;
    const scaledWidth = image.width * scale;

    if (currentWidth + scaledWidth + gap * currentRow.length > containerWidth && currentRow.length > 0) {
      const totalAspectRatio = currentRow.reduce((sum, img) => sum + img.width / img.height, 0);

      const adjustedRow: JustifiedImage[] = currentRow.map((img) => {
        const ratio = img.width / img.height;
        const width = (containerWidth - gap * (currentRow.length - 1)) * (ratio / totalAspectRatio);
        return { ...img, width, height: rowHeight };
      });

      rows.push(adjustedRow);
      currentRow = [];
      currentWidth = 0;
    }

    currentRow.push(image);
    currentWidth += scaledWidth;
  }

  if (currentRow.length > 0) {
    const adjustedRow: JustifiedImage[] = currentRow.map((img) => {
      const scale = rowHeight / img.height;
      return {
        ...img,
        width: img.width * scale,
        height: rowHeight,
      };
    });
    rows.push(adjustedRow);
  }

  return rows;
}