import React, { Children } from "react";

import { Stack } from "../Stack";
import { ViewProps } from "../View";

function chunk<T>(array: T[], size: number): T[][] {
  const result = [];
  for (let i = 0; i < array.length; i += size) {
    result.push(array.slice(i, i + size));
  }
  return result;
}

type Props = {
  children?: React.ReactNode;
  columns: number;
  gap?: number;
} & ViewProps;

const Tiles = ({ children, columns, gap, ...viewProps }: Props) => {
  return (
    <Stack gap={gap} {...viewProps}>
      {chunk(Children.toArray(children).filter(Boolean), columns).map(
        (childrenChunk, index) => (
          <Stack
            inline
            key={`stack-${index}`}
            children={childrenChunk}
            gap={gap}
          />
        )
      )}
    </Stack>
  );
};

export default Tiles;
