import { forwardRef } from "react";

/**
 * Checkbox
 *
 * size:          "lg" | "xl" | (default)
 * label:         string | ReactNode - visible label; omit and pass aria-label via props instead
 * labelHidden:   boolean - visually hides the label (sr-only) while keeping it accessible
 * indeterminate: boolean - sets the indeterminate DOM property
 */
const Checkbox = forwardRef(function Checkbox(
  {
    size,
    label,
    labelHidden = false,
    indeterminate = false,
    className = "",
    ...props
  },
  ref
) {
  const inputClasses = [
    "prs-checkbox",
    size === "lg" && "prs-checkbox-lg",
    size === "xl" && "prs-checkbox-xl",
    indeterminate && "prs-checkbox_indeterminate",
    className,
  ]
    .filter(Boolean)
    .join(" ");

  // sync the indeterminate DOM property - can't be set via HTML attribute
  const setRef = (el) => {
    if (el) el.indeterminate = indeterminate;
    if (typeof ref === "function") ref(el);
    else if (ref) ref.current = el;
  };

  const input = (
    <input
      type="checkbox"
      ref={setRef}
      className={inputClasses}
      {...props}
    />
  );

  if (!label) return input;

  return (
    <label className="prs-checkbox-label">
      {input}
      <span className={labelHidden ? "sr-only" : "prs-label-text"}>
        {label}
      </span>
    </label>
  );
});

export default Checkbox;
