import * as React from 'react';
import { Slot } from '@radix-ui/react-slot';
import { cva, type VariantProps } from 'class-variance-authority';

import { cn } from '@/lib/utils';

/**
 * shadcn "new-york" button, retuned to PIG's tokens.
 *
 * Note `accent` in tailwind.config.js is the SUBTLE hover surface, not the
 * brand — that mapping is deliberate and documented there. So the solid CTA
 * uses `bg-brand text-accent-on`, never `bg-accent`.
 */
const buttonVariants = cva(
  'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors duration-1 ease-enter disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0',
  {
    variants: {
      variant: {
        default: 'bg-brand text-accent-on shadow-sm hover:bg-brand/90',
        secondary: 'bg-surface-2 text-fg hover:bg-surface-2/70',
        outline: 'border border-border bg-surface text-fg hover:bg-surface-2',
        ghost: 'text-fg hover:bg-surface-2',
        subtle: 'bg-accent-subtle text-accent-fg hover:bg-accent-subtle/70',
        destructive: 'bg-danger text-white shadow-sm hover:bg-danger/90',
        link: 'text-accent-fg underline-offset-4 hover:underline',
      },
      size: {
        // `h-9` is 36px, which is fine for a mouse and too small for a thumb.
        // Anything a phone visitor taps gets `size="touch"` or the `.tap`
        // helper on top — see SiteHeader.
        sm: 'h-8 rounded-md px-3 text-xs [&_svg]:size-3.5',
        default: 'h-9 px-4 py-2 [&_svg]:size-4',
        lg: 'h-11 rounded-lg px-6 [&_svg]:size-4',
        touch: 'min-h-11 px-4 py-2 [&_svg]:size-4',
        icon: 'size-9 [&_svg]:size-4',
        'icon-touch': 'size-11 [&_svg]:size-[1.125rem]',
      },
    },
    defaultVariants: { variant: 'default', size: 'default' },
  },
);

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

function Button({ className, variant, size, asChild = false, ...props }: ButtonProps) {
  const Comp = asChild ? Slot : 'button';
  return <Comp className={cn(buttonVariants({ variant, size }), className)} {...props} />;
}

export { Button, buttonVariants };
