export interface VirtualGridRow<T> {
  key: string;
  items: T[];
  startIndex: number;
}

export function calculateVirtualGridColumnCount(
  width: number,
  minimumColumnWidth: number,
  maximumColumns: number,
  gap: number,
): number {
  if (!Number.isFinite(width) || width <= 0) return 1;
  const safeMinimum = Math.max(1, minimumColumnWidth);
  const safeMaximum = Math.max(1, Math.floor(maximumColumns));
  const safeGap = Math.max(0, gap);
  return Math.max(1, Math.min(safeMaximum, Math.floor((width + safeGap) / (safeMinimum + safeGap))));
}

export function chunkVirtualGridItems<T>(
  items: T[],
  columns: number,
  itemKey: (item: T) => string,
): Array<VirtualGridRow<T>> {
  const safeColumns = Math.max(1, Math.floor(columns));
  const rows: Array<VirtualGridRow<T>> = [];
  for (let startIndex = 0; startIndex < items.length; startIndex += safeColumns) {
    const rowItems = items.slice(startIndex, startIndex + safeColumns);
    rows.push({
      key: `${startIndex}:${rowItems.map(itemKey).join("|")}`,
      items: rowItems,
      startIndex,
    });
  }
  return rows;
}

export function calculateVirtualGridRowWindowLimit(itemWindowLimit: number | undefined, columns: number): number | undefined {
  if (!itemWindowLimit || itemWindowLimit <= 0) return undefined;
  return Math.max(1, Math.ceil(itemWindowLimit / Math.max(1, Math.floor(columns))));
}
