// shadcn-style Checkbox — native `<input type=checkbox>` (no Radix dep)
// with indeterminate support. Drives the check / dash glyphs purely via
// CSS peer variants so it can't desync from the input's real state.

import { useEffect, useRef, type InputHTMLAttributes, type ReactNode } from 'react'
import { cn } from '../cn'

export interface CheckboxProps extends InputHTMLAttributes<HTMLInputElement> {
  /** Tri-state middle: renders a dash. Wired to the DOM `indeterminate`
   *  property (not an attribute) via a ref effect. */
  readonly indeterminate?: boolean
}

export const Checkbox = ({ className, indeterminate, ...props }: CheckboxProps): ReactNode => {
  const ref = useRef<HTMLInputElement>(null)
  useEffect(() => {
    if (ref.current) ref.current.indeterminate = indeterminate === true
  }, [indeterminate])

  return (
    <span className="relative inline-flex size-4 shrink-0 items-center justify-center">
      <input
        ref={ref}
        type="checkbox"
        data-slot="checkbox"
        className={cn(
          'peer size-4 appearance-none rounded-[4px] border shadow-xs outline-none',
          'border-input bg-transparent dark:bg-input/30',
          'checked:bg-primary checked:border-primary',
          'indeterminate:bg-primary indeterminate:border-primary',
          'transition-[color,box-shadow]',
          'focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]',
          'disabled:cursor-not-allowed disabled:opacity-50',
          'cursor-pointer',
          className,
        )}
        {...props}
      />
      {/* checkmark — visible only when checked (and not indeterminate) */}
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth={3}
        strokeLinecap="round"
        strokeLinejoin="round"
        className="pointer-events-none absolute hidden size-3 text-primary-foreground peer-checked:peer-indeterminate:hidden peer-checked:block"
      >
        <path d="M20 6 9 17l-5-5" />
      </svg>
      {/* indeterminate dash */}
      <span className="pointer-events-none absolute hidden h-[2px] w-2.5 rounded-full bg-primary-foreground peer-indeterminate:block" />
    </span>
  )
}
