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

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

const badgeVariants = cva(
  "inline-flex items-center rounded-md px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
  {
    variants: {
      variant: {
        default: "bg-primary text-primary-foreground shadow hover:bg-primary/80",
        secondary: "border", // Added border back
        destructive: "bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",
        outline: "border text-foreground",
        success: "border", // Added border
        warning: "border", // Added border
        error: "border", // Added border
        info: "border", // Added border
        neutral: "border", // Added border
      },
      size: {
        sm: "px-2 py-0.5 text-xs",
        md: "px-2.5 py-0.5 text-xs",
        lg: "px-3 py-1 text-sm",
      },
    },
    defaultVariants: {
      variant: "default",
      size: "md",
    },
  },
)

export interface BadgeProps extends React.HTMLAttributes<HTMLDivElement>, VariantProps<typeof badgeVariants> {}

function Badge({ className, variant, size, style, ...props }: BadgeProps) {
  // Apply semantic colors for semantic variants
  const semanticVariants = ["success", "warning", "error", "info", "neutral"]
  const isSemanticVariant = variant && semanticVariants.includes(variant)

  // Apply CSS variable for secondary variant
  const isSecondaryVariant = variant === "secondary"

  let appliedStyle = style

  if (isSemanticVariant) {
    appliedStyle = {
      backgroundColor: `var(--semantic-${variant}-bg)`,
      color: `var(--semantic-${variant}-text)`,
      borderColor: `var(--semantic-${variant}-border)`, // Use the defined border color instead of background
      ...style,
    }
  } else if (isSecondaryVariant) {
    const bgColor = `hsl(var(--primary) / 0.1)`
    appliedStyle = {
      backgroundColor: bgColor,
      color: `hsl(var(--primary))`,
      borderColor: bgColor, // Use same color as background for border
      ...style,
    }
  }

  return <div className={cn(badgeVariants({ variant, size }), className)} style={appliedStyle} {...props} />
}

export { Badge, badgeVariants }
