import type { ReactNode } from 'react';
import { Reveal } from '@/site/components/motion/reveal';
import { cx } from '@/site/lib/cx';

/**
 * For every card, how many cards share its row when `count` cards are laid
 * out at most `max` per row. Rows are balanced, so a card is never left
 * alone on the last row: seven cards in threes become 3 + 2 + 2 (not
 * 3 + 3 + 1), ten become 3 + 3 + 2 + 2.
 */
export function rowSizes(count: number, max: number): number[] {
    const rows = Math.ceil(count / max);
    const base = Math.floor(count / rows);
    const fuller = count % rows; // this many rows hold one card more

    const sizes: number[] = [];

    for (let row = 0; row < rows; row++) {
        const size = base + (row < fuller ? 1 : 0);

        for (let card = 0; card < size; card++) {
            sizes.push(size);
        }
    }

    return sizes;
}

/* Column spans on the 12-column grid, by the number of cards in the row. */
const pairSpan: Record<number, string> = {
    1: 'sm:col-span-12',
    2: 'sm:col-span-6',
};

const wideSpan: Record<number, string> = {
    1: 'xl:col-span-12',
    2: 'xl:col-span-6',
    3: 'xl:col-span-4',
    4: 'xl:col-span-3',
};

type CardGridProps<T> = {
    items: T[];
    /** Most cards per row on wide screens (two per row on tablets, one on phones). */
    columns?: 3 | 4;
    itemKey: (item: T) => string;
    children: (item: T, index: number) => ReactNode;
    className?: string;
    itemClassName?: string;
};

/**
 * A list of cards, revealed on scroll, whose rows always look complete
 * whatever the number of cards (see `rowSizes`) — the content comes from
 * the database, so the count is not known in advance.
 */
export function CardGrid<T>({
    items,
    columns = 3,
    itemKey,
    children,
    className,
    itemClassName,
}: CardGridProps<T>) {
    const pairs = rowSizes(items.length, 2);
    const wide = rowSizes(items.length, columns);

    return (
        <ul className={cx('grid gap-5 sm:grid-cols-12', className)}>
            {items.map((item, index) => (
                <Reveal
                    as="li"
                    key={itemKey(item)}
                    delay={(index % columns) * 70}
                    className={cx(
                        pairSpan[pairs[index]],
                        wideSpan[wide[index]],
                        itemClassName,
                    )}
                >
                    {children(item, index)}
                </Reveal>
            ))}
        </ul>
    );
}
