import { forwardRef } from 'react';
import * as CheckboxPrimitive from '@radix-ui/react-checkbox';
import { Check } from 'lucide-react';
import { cn } from '../../lib/utils.js';

/**
 * Accessible, design-token styled checkbox.
 * Wraps Radix Checkbox so it is keyboard-accessible with a visible focus ring.
 * Accepts `checked`, `onCheckedChange` (Radix) and, for convenience, `onChange`
 * (called with a synthetic-ish `{ target: { checked } }`) so it can drop into
 * places that previously used a bare <input type="checkbox">.
 */
const Checkbox = forwardRef(function Checkbox(
  { className, onCheckedChange, onChange, ...props },
  ref
) {
  const handleCheckedChange = (checked) => {
    onCheckedChange?.(checked);
    onChange?.({ target: { checked } });
  };

  return (
    <CheckboxPrimitive.Root
      ref={ref}
      onCheckedChange={handleCheckedChange}
      className={cn(
        'peer inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-[4px] border border-border bg-card transition-colors',
        'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background',
        'hover:border-primary/60',
        'disabled:cursor-not-allowed disabled:opacity-50',
        'data-[state=checked]:border-primary data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground',
        className
      )}
      {...props}
    >
      <CheckboxPrimitive.Indicator className="flex items-center justify-center text-current">
        <Check className="h-3 w-3" strokeWidth={3} />
      </CheckboxPrimitive.Indicator>
    </CheckboxPrimitive.Root>
  );
});

export { Checkbox };
