import * as React from 'react'
import { Slot } from '@radix-ui/react-slot'
import { cn } from './cva'

type SpaceToken = '1' | '2' | '3' | '4' | '5' | '6' | '8' | '10' | '12'
type Align = 'start' | 'center' | 'end'
type Justify = 'start' | 'center' | 'end' | 'between'
type CSSVars = React.CSSProperties & Record<`--${string}`, string>

export interface ClusterProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'style'> {
  asChild?: boolean
  gap?: SpaceToken
  align?: Align
  justify?: Justify
  style?: React.CSSProperties
}

const alignClass: Record<Align, string> = {
  start: 'items-start',
  center: 'items-center',
  end: 'items-end',
}

const justifyClass: Record<Justify, string> = {
  start: 'justify-start',
  center: 'justify-center',
  end: 'justify-end',
  between: 'justify-between',
}

export const Cluster = React.forwardRef<HTMLDivElement, ClusterProps>(
  ({ asChild, className, gap = '3', align = 'center', justify = 'start', style, ...props }, ref) => {
    const Comp = asChild ? Slot : 'div'
    const clusterStyle: CSSVars = {
      '--cluster-gap': `var(--mod-space-${gap})`,
      gap: 'var(--cluster-gap)',
      minWidth: 0,
      ...style,
    }

    return (
      <Comp
        ref={ref}
        className={cn('@container flex flex-wrap', alignClass[align], justifyClass[justify], className)}
        style={clusterStyle}
        {...props}
      />
    )
  },
)

Cluster.displayName = 'Cluster'
