import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"

import { cn } from "@/lib/utils"

const dividerVariants = cva("shrink-0 border-0 p-0", {
  variants: {
    direction: {
      horizontal:
        "h-[var(--bh-space-xxxs-1)] w-[var(--bh-space-15xl-224)]",
      vertical:
        "h-[var(--bh-space-15xl-224)] w-[var(--bh-space-xxxs-1)]",
    },
    type: {
      solid: "bg-[var(--bh-border-subtle)]",
      dotted: "bg-transparent",
    },
  },
  defaultVariants: {
    direction: "horizontal",
    type: "solid",
  },
})

type DividerDirection = NonNullable<
  VariantProps<typeof dividerVariants>["direction"]
>
type DividerType = NonNullable<VariantProps<typeof dividerVariants>["type"]>

type DividerProps = React.ComponentProps<"div"> &
  VariantProps<typeof dividerVariants> & {
    decorative?: boolean
  }

function Divider({
  className,
  direction = "horizontal",
  type = "solid",
  decorative = false,
  role,
  style,
  "aria-hidden": ariaHidden,
  ...props
}: DividerProps) {
  const selectedDirection = direction || "horizontal"
  const selectedType = type || "solid"
  const dottedStyle =
    selectedType === "dotted"
      ? getDottedDividerStyle(selectedDirection)
      : undefined

  return (
    <div
      aria-hidden={decorative ? true : ariaHidden}
      aria-orientation={decorative ? undefined : selectedDirection}
      data-direction={selectedDirection}
      data-slot="divider"
      data-type={selectedType}
      role={decorative ? "presentation" : role || "separator"}
      style={{ ...dottedStyle, ...style }}
      className={cn(
        dividerVariants({
          direction: selectedDirection,
          type: selectedType,
          className,
        })
      )}
      {...props}
    />
  )
}

function getDottedDividerStyle(direction: DividerDirection): React.CSSProperties {
  const axis = direction === "vertical" ? "bottom" : "right"

  return {
    backgroundImage: `repeating-linear-gradient(to ${axis}, var(--bh-border-subtle) 0 var(--bh-space-xxs-2), transparent var(--bh-space-xxs-2) calc(var(--bh-space-xxs-2) + var(--bh-space-xxs-2)))`,
  }
}

export { Divider, dividerVariants }
export type { DividerDirection, DividerProps, DividerType }
