// @design-system: layout/Grid
/**
 * Grid - CSS Grid container using token-based gap and column counts.
 *
 * @example
 * <Grid cols={2} gap="4">
 *   <MetricTile />
 *   <MetricTile />
 * </Grid>
 */

import { type ReactNode } from 'react';
import { cn } from '@/lib/cn';

type SpacingKey = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '8' | '10' | '12';
type ColsKey = 1 | 2 | 3 | 4 | 5 | 6 | 12;
type LgColsKey = 2 | 3 | 4 | 5 | 6 | 8;

const lgColsMap: Record<LgColsKey, string> = {
  2: 'lg:grid-cols-2',
  3: 'lg:grid-cols-3',
  4: 'lg:grid-cols-4',
  5: 'lg:grid-cols-5',
  6: 'lg:grid-cols-6',
  8: 'lg:grid-cols-8',
};

const gapMap: Record<SpacingKey, string> = {
  '0': 'gap-0',
  '1': 'gap-1',
  '2': 'gap-2',
  '3': 'gap-3',
  '4': 'gap-4',
  '5': 'gap-5',
  '6': 'gap-6',
  '8': 'gap-8',
  '10': 'gap-10',
  '12': 'gap-12',
};

const colsMap: Record<ColsKey, string> = {
  1: 'grid-cols-1',
  2: 'grid-cols-2',
  3: 'grid-cols-3',
  4: 'grid-cols-4',
  5: 'grid-cols-5',
  6: 'grid-cols-6',
  12: 'grid-cols-12',
};

export interface GridProps {
  children: ReactNode;
  cols?: ColsKey;
  /** Responsive column count applied at lg breakpoint (64rem). */
  lgCols?: LgColsKey;
  gap?: SpacingKey;
  className?: string;
  as?: React.ElementType;
}

export function Grid({
  children,
  cols = 2,
  lgCols,
  gap = '4',
  className,
  as: Tag = 'div',
}: GridProps) {
  return (
    <Tag className={cn('grid', colsMap[cols], lgCols && lgColsMap[lgCols], gapMap[gap], className)}>
      {children}
    </Tag>
  );
}
