import { Slot } from "@radix-ui/react-slot";
import { type VariantProps, cva } from "class-variance-authority";
import { Loader2 } from "lucide-react";
import * as React from "react";
import { cn } from "@/modules/ui/lib/utils";

// Keyboard focus is a ring set off by a gap in the page colour, so it reads on every variant: a
// primary button's dark fill, then the gap, then the ring (WCAG 2.4.7 focus visible).
// Hover is gated on `not-disabled:` (`:not(:disabled)`), never `enabled:`. `:enabled` only matches
// form controls, so every `<Button asChild><Link/></Button>` renders an `<a>` that can never match
// it — the classes sit in the DOM and do nothing (ENG-3138). `:not(:disabled)` matches both a live
// `<button>` and an `<a>`, and still drops out on a disabled `<button>`.
const buttonVariants = cva(
  "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
  {
    variants: {
      variant: {
        default: "bg-primary text-primary-foreground not-disabled:hover:bg-primary/80",
        destructive: "bg-destructive text-destructive-foreground not-disabled:hover:bg-destructive/80",
        outline:
          "border border-input bg-background not-disabled:hover:bg-accent not-disabled:hover:text-accent-foreground",
        secondary:
          "bg-secondary text-secondary-foreground not-disabled:hover:bg-secondary/30 border border-primary/5 not-disabled:hover:border-primary/20",
        // AI flavours. These deliberately step outside the Quiet Primary Rule: a generative action
        // is a different class of thing from a save, and marking it is the point. Reserved for
        // actions that actually invoke a model — a save that follows one stays `default`.
        "ai-primary": "bg-ai-strong text-white not-disabled:hover:bg-ai-strong/90",
        "ai-secondary":
          "bg-ai-subtle text-ai-dark border border-ai-dark/10 not-disabled:hover:bg-ai-subtle/60 not-disabled:hover:border-ai-dark/20",
        ghost: "not-disabled:hover:bg-accent not-disabled:hover:text-accent-foreground text-primary",
        link: "text-primary underline-offset-4 not-disabled:hover:underline",
      },
      size: {
        default: "h-9 px-4 py-2",
        sm: "h-8 rounded-md px-3 text-xs",
        lg: "h-10 rounded-md px-8",
        icon: "h-9 w-9",
        tall: "h-10 rounded-md px-3 text-xs",
      },
      loading: {
        true: "relative cursor-not-allowed opacity-50",
      },
    },
    defaultVariants: {
      variant: "default",
      size: "default",
      loading: false,
    },
  }
);

export interface ButtonProps
  extends React.ButtonHTMLAttributes<HTMLButtonElement>, VariantProps<typeof buttonVariants> {
  readonly asChild?: boolean;
  readonly loading?: boolean;
}

const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
  ({ className, variant, size, loading, asChild = false, disabled, children, ...props }, ref) => {
    const Comp = asChild ? Slot : "button";
    return (
      <Comp
        className={cn(buttonVariants({ variant, size, loading, className }))}
        ref={ref}
        {...props}
        disabled={loading || disabled}>
        {loading ? (
          // Keep the label in the layout but invisible and center the spinner over it, so the
          // button's width never changes between idle and loading (no layout shift).
          <>
            <Loader2 className="absolute inset-0 m-auto animate-spin" />
            <span className="invisible inline-flex items-center gap-2">{children}</span>
          </>
        ) : (
          children
        )}
      </Comp>
    );
  }
);
Button.displayName = "Button";

export { Button, buttonVariants };
