import type { ComponentChildren, JSX } from 'preact';
import { cn } from './cn';

export type BadgeVariant = 'neutral' | 'primary' | 'success' | 'danger' | 'warning' | 'surface';
export type BadgeSize = 'xs' | 'sm';

export type BadgeProps = JSX.HTMLAttributes<HTMLSpanElement> & {
  variant?: BadgeVariant;
  size?: BadgeSize;
  dotColor?: string;
  icon?: ComponentChildren;
};

const BADGE_VARIANTS: Record<BadgeVariant, string> = {
  neutral: 'ask-bg-surface ask-text-textMuted',
  primary: 'ask-bg-primarySoft ask-text-primary',
  success: 'ask-bg-success/10 ask-text-success',
  danger: 'ask-bg-danger/10 ask-text-danger',
  warning: 'ask-bg-warning/10 ask-text-text',
  surface: 'ask-bg-surfaceAlt ask-text-textMuted ask-border ask-border-borderSubtle',
};

const BADGE_SIZES: Record<BadgeSize, string> = {
  xs: 'ask-px-2 ask-py-0.5 ask-text-[10px]',
  sm: 'ask-px-2.5 ask-py-1 ask-text-[11px]',
};

export function Badge({
  className,
  children,
  variant = 'neutral',
  size = 'xs',
  dotColor,
  icon,
  ...props
}: BadgeProps) {
  return (
    <span
      className={cn(
        'ask-inline-flex ask-max-w-full ask-items-center ask-gap-1.5 ask-rounded-full ask-font-medium ask-leading-4',
        BADGE_VARIANTS[variant],
        BADGE_SIZES[size],
        className,
      )}
      {...props}
    >
      {dotColor ? <span className="ask-h-2 ask-w-2 ask-shrink-0 ask-rounded-full" style={{ backgroundColor: dotColor }} /> : null}
      {icon ? <span className="ask-flex ask-shrink-0 ask-items-center ask-justify-center">{icon}</span> : null}
      {children !== undefined && children !== null && children !== false ? <span className="ask-min-w-0 ask-truncate">{children}</span> : null}
    </span>
  );
}
