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 Orientation = 'horizontal' | 'vertical'
type CSSVars = React.CSSProperties & Record<`--${string}`, string>

export interface DividerProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'style'> {
  asChild?: boolean
  gap?: SpaceToken
  orientation?: Orientation
  style?: React.CSSProperties
}

export const Divider = React.forwardRef<HTMLDivElement, DividerProps>(
  ({ asChild, className, gap = '4', orientation = 'horizontal', style, ...props }, ref) => {
    const Comp = asChild ? Slot : 'div'
    const dividerStyle: CSSVars = {
      '--divider-gap': `var(--mod-space-${gap})`,
      backgroundColor: 'var(--mod-color-border)',
      blockSize: orientation === 'horizontal' ? 'var(--mod-border-thin)' : '100%',
      inlineSize: orientation === 'horizontal' ? '100%' : 'var(--mod-border-thin)',
      marginBlock: orientation === 'horizontal' ? 'var(--divider-gap)' : undefined,
      marginInline: orientation === 'vertical' ? 'var(--divider-gap)' : undefined,
      minWidth: 0,
      ...style,
    }

    return (
      <Comp
        ref={ref}
        role="separator"
        aria-orientation={orientation}
        className={cn('@container shrink-0 self-stretch', className)}
        style={dividerStyle}
        {...props}
      />
    )
  },
)

Divider.displayName = 'Divider'
