import { cn } from '@/lib/utils';
import { cva, type VariantProps } from 'class-variance-authority';
import { ButtonHTMLAttributes, forwardRef } from 'react';

export const buttonVariants = cva(
    'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-lg text-sm font-medium transition-all duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50 active:scale-[0.98] [&_svg]:size-4 [&_svg]:shrink-0',
    {
        variants: {
            variant: {
                primary: 'bg-primary text-primary-foreground shadow-sm hover:opacity-90',
                secondary: 'border border-border bg-card text-foreground hover:bg-accent',
                ghost: 'text-muted-foreground hover:bg-accent hover:text-foreground',
                danger: 'bg-destructive text-white hover:opacity-90',
            },
            size: { sm: 'h-8 px-3', md: 'h-10 px-4', lg: 'h-11 px-5 text-[15px]', icon: 'size-9' },
        },
        defaultVariants: { variant: 'primary', size: 'md' },
    },
);

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

export const Button = forwardRef<HTMLButtonElement, ButtonProps>(({ className, variant, size, loading, children, disabled, ...props }, ref) => (
    <button ref={ref} className={cn(buttonVariants({ variant, size }), className)} disabled={disabled || loading} {...props}>
        {loading && <span className="size-4 animate-spin rounded-full border-2 border-current border-t-transparent" />}
        {children}
    </button>
));
Button.displayName = 'Button';
