/**
 * UI primitives, in the shadcn idiom — copied-in components you own rather
 * than a dependency you configure. Kept in one file because there are few
 * enough that a directory of six-line modules would be worse.
 *
 * Every interactive element clears a 44px touch target, which is the
 * documented iOS minimum and the practical difference between a control that
 * works on a phone and one that is merely present on it.
 */
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
import { cva, type VariantProps } from 'class-variance-authority';
import { Slot } from '@radix-ui/react-slot';
import {
  forwardRef,
  type ButtonHTMLAttributes,
  type HTMLAttributes,
  type InputHTMLAttributes,
  type ReactNode,
} from 'react';

export function cn(...inputs: ClassValue[]): string {
  return twMerge(clsx(inputs));
}

// ------------------------------------------------------------------- button

/**
 * One button, two vocabularies.
 *
 * There used to be two Button *components* — this one and a verbatim shadcn
 * copy at `@/components/ui/button` with a different variant vocabulary
 * (`default`/`destructive`/`link`) and a 36px size scale that fails PIG's own
 * 44px touch-target rule. Two implementations of the same control drift, and
 * these two already had: one grew a `danger` variant, the other a `link`.
 *
 * They are now a single cva. Both vocabularies are declared here as aliases of
 * the same classes, so `variant="primary"` and `variant="default"` are the
 * same button, and `@/components/ui/button` is a re-export that only supplies
 * shadcn's different *default* variant. The remaining work is to retire the
 * shadcn names at the three call sites that use them and delete the shim.
 */
const buttonVariants = cva(
  'inline-flex items-center justify-center gap-2 rounded-lg text-sm font-medium ' +
    'transition-colors disabled:pointer-events-none disabled:opacity-50 ' +
    '[&_svg]:shrink-0 ' +
    // touch-manipulation removes the 300ms tap delay that older mobile Safari
    // applies while waiting to see whether a tap is a double-tap zoom.
    'touch-manipulation select-none whitespace-nowrap',
  {
    variants: {
      variant: {
        primary: 'bg-primary text-primary-foreground shadow-sm hover:opacity-90 active:opacity-80',
        secondary: 'bg-surface-2 text-fg hover:bg-border active:bg-border',
        outline: 'border border-border bg-transparent hover:bg-surface-2',
        ghost: 'bg-transparent hover:bg-surface-2',
        danger: 'bg-danger text-white hover:opacity-90',
        /* shadcn's vocabulary, mapped onto the same three treatments. */
        default: 'bg-primary text-primary-foreground shadow-sm hover:opacity-90 active:opacity-80',
        destructive: 'bg-danger text-white hover:opacity-90',
        link: 'bg-transparent text-accent-fg underline-offset-4 hover:underline',
      },
      size: {
        // min-h keeps the target tappable even when the label is short.
        sm: 'h-11 min-h-[44px] px-3 text-xs',
        md: 'h-11 min-h-[44px] px-4',
        lg: 'h-12 min-h-[48px] px-6 text-base',
        icon: 'h-11 w-11 min-h-[44px] min-w-[44px] p-0',
        /* shadcn's `default` size. Deliberately PIG's height, not 36px. */
        default: 'h-11 min-h-[44px] px-4',
      },
    },
    defaultVariants: { variant: 'secondary', size: 'md' },
  },
);

export { buttonVariants };

export interface ButtonProps
  extends ButtonHTMLAttributes<HTMLButtonElement>,
    VariantProps<typeof buttonVariants> {
  /** Render the child element instead of a `<button>`, keeping the classes. */
  asChild?: boolean;
}

export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
  ({ className, variant, size, asChild = false, ...props }, ref) => {
    const Component = asChild ? Slot : 'button';
    return (
      <Component
        ref={ref}
        className={cn(buttonVariants({ variant, size }), className)}
        {...props}
      />
    );
  },
);
Button.displayName = 'Button';

// -------------------------------------------------------------------- input

export const Input = forwardRef<HTMLInputElement, InputHTMLAttributes<HTMLInputElement>>(
  ({ className, ...props }, ref) => (
    <input
      ref={ref}
      className={cn(
        'h-11 w-full rounded-lg border border-border bg-surface px-3 text-fg',
        'placeholder:text-muted focus-visible:border-accent',
        // The base stylesheet enforces a 16px minimum so Safari does not zoom
        // the viewport on focus; this must not override it downward.
        className,
      )}
      {...props}
    />
  ),
);
Input.displayName = 'Input';

// --------------------------------------------------------------------- card

/**
 * `min-w-0` is on the base class deliberately, not left to each call site.
 *
 * A grid or flex child defaults to `min-width: auto`, meaning it refuses to
 * shrink below its content — and cards routinely contain something
 * unshrinkable (a `tabular-nums` figure, a `whitespace-nowrap` badge, a long
 * unbroken title). The result is a card wider than its column, which drags the
 * whole page into horizontal scrolling on a phone.
 *
 * This has now been fixed three separate times at individual call sites, which
 * is the signal that it belongs here instead. `min-width: 0` is inert for a
 * block-level card outside a flex or grid container, so applying it always
 * costs nothing and removes the entire class of bug.
 */
export function Card({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
  return <div className={cn('card min-w-0', className)} {...props} />;
}

export function CardHeader({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
  return <div className={cn('flex flex-col gap-1 p-4 sm:p-5', className)} {...props} />;
}

export function CardTitle({ className, ...props }: HTMLAttributes<HTMLHeadingElement>) {
  return <h3 className={cn('font-semibold leading-tight', className)} {...props} />;
}

export function CardContent({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
  return <div className={cn('p-4 pt-0 sm:p-5 sm:pt-0', className)} {...props} />;
}

export function CardFooter({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
  return <div className={cn('flex items-center gap-3 p-4 pt-0 sm:p-5 sm:pt-0', className)} {...props} />;
}

// -------------------------------------------------------------------- badge

const badgeVariants = cva(
  'inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium',
  {
    variants: {
      tone: {
        neutral: 'bg-surface-2 text-muted',
        accent: 'bg-accent-subtle text-accent-fg',
        positive: 'bg-positive/10 text-positive',
        warning: 'bg-warning/10 text-warning',
        danger: 'bg-danger/10 text-danger',
        info: 'bg-info/10 text-info',
      },
    },
    defaultVariants: { tone: 'neutral' },
  },
);

export function Badge({
  className,
  tone,
  ...props
}: HTMLAttributes<HTMLSpanElement> & VariantProps<typeof badgeVariants>) {
  return <span className={cn(badgeVariants({ tone }), className)} {...props} />;
}

// --------------------------------------------------------------------- stat

/**
 * A single headline number.
 *
 * `nums` applies tabular figures so a value does not jitter horizontally as it
 * updates — which it does, on a dashboard that refreshes while someone is
 * looking at it.
 */
export function Stat({
  label,
  value,
  hint,
  tone,
}: {
  label: string;
  value: ReactNode;
  hint?: ReactNode;
  tone?: 'positive' | 'warning' | 'danger' | 'default';
}) {
  const toneClass =
    tone === 'positive'
      ? 'text-positive'
      : tone === 'warning'
        ? 'text-warning'
        : tone === 'danger'
          ? 'text-danger'
          : 'text-fg';

  return (
    <div className="card p-4">
      <div className="text-xs font-medium uppercase tracking-wide text-muted">{label}</div>
      <div className={cn('nums mt-1 text-2xl font-semibold leading-tight sm:text-3xl', toneClass)}>
        {value}
      </div>
      {hint ? <div className="mt-1 text-xs text-muted">{hint}</div> : null}
    </div>
  );
}

// ------------------------------------------------------------------ skeleton

export function Skeleton({ className }: { className?: string }) {
  return <div className={cn('animate-pulse rounded-md bg-surface-2', className)} />;
}

// --------------------------------------------------------------- empty state

export function EmptyState({
  icon,
  title,
  description,
  action,
}: {
  icon?: ReactNode;
  title: string;
  description?: string;
  action?: ReactNode;
}) {
  return (
    <div className="flex flex-col items-center justify-center gap-3 px-6 py-12 text-center">
      {icon ? <div className="text-muted">{icon}</div> : null}
      <div>
        <p className="font-medium">{title}</p>
        {description ? (
          <p className="mx-auto mt-1 max-w-sm text-sm text-muted">{description}</p>
        ) : null}
      </div>
      {action}
    </div>
  );
}

// -------------------------------------------------------- confidence marker

/**
 * Provenance, shown rather than hidden.
 *
 * PIG holds records about real people assembled from public sources, and some
 * rest on a single weak citation. Presenting those with the same visual weight
 * as a corroborated record is how a CRM quietly becomes misinformation — so
 * anything short of `confirmed` is labelled wherever it appears.
 */
export function ConfidenceBadge({ confidence }: { confidence: string }) {
  if (confidence === 'confirmed') return null;
  const tone =
    confidence === 'probable' ? 'info' : confidence === 'disputed' ? 'danger' : 'warning';
  const label =
    confidence === 'probable'
      ? 'Probable'
      : confidence === 'disputed'
        ? 'Disputed'
        : 'Unverified';
  return (
    <Badge tone={tone} title="How well-sourced this record is">
      {label}
    </Badge>
  );
}
