// packages/core/src/components/form/form-field.tsx
import type { JSX } from "solid-js";
import { createUniqueId } from "solid-js";
import { useFormContext, FormFieldContextProvider, type FormFieldContextValue } from "./form-context";
import type { FormFieldProps } from "./form.props";

export type { FormFieldProps };

/**
 * Wraps a single form field. Generates unique IDs for the control, description,
 * and error message elements to enable accessible ARIA linking. Triggers
 * field-level validation on blur or change when validateOn is set accordingly.
 */
export function FormField(props: FormFieldProps): JSX.Element {
  const formCtx = useFormContext();
  const baseId = createUniqueId();
  const controlId = `${baseId}-control`;
  const descriptionId = `${baseId}-description`;
  const errorId = `${baseId}-error`;

  const fieldCtx: FormFieldContextValue = {
    name: props.name,
    controlId,
    descriptionId,
    errorId,
    errors: () => formCtx.getFieldErrors(props.name),
  };

  return (
    <FormFieldContextProvider value={fieldCtx}>
      {props.children}
    </FormFieldContextProvider>
  );
}
