// packages/core/src/components/form/form-control.tsx
import type { JSX } from "solid-js";
import { useFormFieldContext } from "./form-context";
import type { FormControlProps } from "./form.props";

export type { FormControlProps };

/** Builds the aria-describedby string combining description and error IDs. */
function buildDescribedBy(descId: string, errorId: string, hasErrors: boolean): string | undefined {
  if (hasErrors) return `${descId} ${errorId}`;
  return descId;
}

/**
 * Render-prop wrapper that injects accessible props (id, name, aria-describedby,
 * aria-invalid) into the field's control element.
 */
export function FormControl(props: FormControlProps): JSX.Element {
  const fieldCtx = useFormFieldContext();

  const hasErrors = (): boolean => fieldCtx.errors().length > 0;
  const describedBy = (): string | undefined =>
    buildDescribedBy(fieldCtx.descriptionId, fieldCtx.errorId, hasErrors());

  return (
    <>
      {props.children({
        id: fieldCtx.controlId,
        name: fieldCtx.name,
        "aria-describedby": describedBy(),
        "aria-invalid": hasErrors() ? true : undefined,
      })}
    </>
  );
}
