'use client';

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

type ChipSize = 'sm' | 'md';

interface ChipProps extends React.HTMLAttributes<HTMLSpanElement> {
  active?: boolean;
  size?: ChipSize;
  className?: string;
  children: React.ReactNode;
  onClick?: () => void;
}

const sizeClasses: Record<ChipSize, string> = {
  sm: 'px-3 py-1 text-xs',
  md: 'px-4 py-1.5 text-sm',
};

const Chip = forwardRef<HTMLSpanElement, ChipProps>(
  (
    {
      active = false,
      size = 'md',
      className,
      children,
      onClick,
      ...props
    },
    ref,
  ) => {
    const isInteractive = typeof onClick === 'function';

    return (
      <span
        ref={ref}
        role={isInteractive ? 'button' : undefined}
        tabIndex={isInteractive ? 0 : undefined}
        onClick={onClick}
        onKeyDown={
          isInteractive
            ? (e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                  e.preventDefault();
                  onClick?.();
                }
              }
            : undefined
        }
        className={cn(
          // Base
          'inline-flex items-center justify-center',
          'rounded-full font-medium',
          'transition-colors duration-150 ease-out',
          'select-none',
          // Size
          sizeClasses[size],
          // State: inactive
          !active && [
            'bg-surface-low text-on-surface',
            isInteractive && 'hover:bg-outline-variant/30 cursor-pointer',
          ],
          // State: active
          active && 'bg-primary/10 text-primary-dark',
          // Focus for interactive
          isInteractive && [
            'outline-none',
            'focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-1',
          ],
          className,
        )}
        {...props}
      >
        {children}
      </span>
    );
  },
);

Chip.displayName = 'Chip';

export default Chip;
export type { ChipProps, ChipSize };
