import { cn } from "@repo/shadcn-ui/lib/utils";
import { type VariantProps, cva } from "class-variance-authority";
import * as React from "react";

/** 1–12 columnas por breakpoint */
export type Cols = Partial<{ base: number; sm: number; md: number; lg: number; xl: number }>;

const gridBase = cva("grid", {
  variants: {
    gap: {
      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",
    },
    align: {
      start: "items-start",
      center: "items-center",
      end: "items-end",
      stretch: "items-stretch",
    },
  },
  defaultVariants: {
    gap: 6,
    align: "stretch",
  },
});

function to12(n?: number) {
  if (!n) return 12;
  return n < 1 ? 1 : n > 12 ? 12 : n;
}

function colsToClasses(cols?: Cols) {
  if (!cols) return "";
  const c: string[] = [];
  if (cols.base) c.push(`grid-cols-${to12(cols.base)}`);
  if (cols.sm) c.push(`sm:grid-cols-${to12(cols.sm)}`);
  if (cols.md) c.push(`md:grid-cols-${to12(cols.md)}`);
  if (cols.lg) c.push(`lg:grid-cols-${to12(cols.lg)}`);
  if (cols.xl) c.push(`xl:grid-cols-${to12(cols.xl)}`);
  return c.join(" ");
}

export interface GridProps
  extends Omit<React.HTMLAttributes<HTMLDivElement>, "children">,
    VariantProps<typeof gridBase> {
  cols?: Cols;
  children?: React.ReactNode;
}

/** Grid genérico: controla columnas visibles por breakpoint */
export function Grid({ className, cols, gap, align, children, ...rest }: GridProps) {
  return (
    <div className={cn(gridBase({ gap, align }), colsToClasses(cols), className)} {...rest}>
      {children}
    </div>
  );
}
