import type { LabelHTMLAttributes, ReactNode } from 'react';
import { forwardRef } from 'react';
import './label.css';

export type LabelProps = {
  children?: ReactNode;
  /** When true, appends the required-indicator asterisk after the label content. */
  required?: boolean;
  /** Visually hide the label while keeping it in the accessibility tree. */
  visuallyHidden?: boolean;
} & Omit<LabelHTMLAttributes<HTMLLabelElement>, 'children'>;

/**
 * Standalone form label with optional {@link required} asterisk. Pass {@link LabelHTMLAttributes.htmlFor}
 * to associate with a control id, or wrap a control as a descendant without `htmlFor`.
 */
export const Label = forwardRef<HTMLLabelElement, LabelProps>(function Label(
  { children, required = false, visuallyHidden = false, className, ...rest },
  ref
) {
  const rootClass = ['ccl-label', visuallyHidden ? 'ccl-label--visually-hidden' : '', className].filter(Boolean).join(' ');

  return (
    <label ref={ref} className={rootClass} {...rest}>
      {children}
      {required ? (
        <span className="ccl-label__required" aria-label="required">
          *
        </span>
      ) : null}
    </label>
  );
});
