import { Slot, Slottable } from "@radix-ui/react-slot";
import { forwardRef } from "react";

import { badgeVariants } from "./badge.variants";
import { cn } from "../lib/cn";
import type { VariantProps } from "../lib/cva";
import { createDataAttributes, createSlot, type AsChildProp } from "../lib/contracts";

export type BadgeProps = React.ComponentPropsWithoutRef<"span"> &
  AsChildProp &
  VariantProps<typeof badgeVariants>;

export const Badge = forwardRef<HTMLSpanElement, BadgeProps>(function Badge(
  {
    asChild = false,
    children,
    className,
    size,
    tone,
    variant,
    ...props
  },
  ref
) {
  const Component = asChild ? Slot : "span";

  return (
    <Component
      {...props}
      {...createSlot("root")}
      {...createDataAttributes({
        size,
        tone,
        variant
      })}
      className={cn(badgeVariants({ size, tone, variant }), className)}
      ref={ref}
    >
      {asChild ? <Slottable>{children}</Slottable> : <span {...createSlot("label")}>{children}</span>}
    </Component>
  );
});
