// packages/core/src/components/text-field/text-field-error-message.tsx
import type { JSX } from "solid-js";
import { Show, createUniqueId, onCleanup, onMount, splitProps } from "solid-js";
import { useTextFieldContext } from "./text-field-context";

export interface TextFieldErrorMessageProps extends JSX.HTMLAttributes<HTMLParagraphElement> {
  children?: JSX.Element;
}

/** Error message shown when the field is invalid. Announced via aria-live. */
export function TextFieldErrorMessage(props: TextFieldErrorMessageProps): JSX.Element {
  const [local, rest] = splitProps(props, ["children"]);
  const ctx = useTextFieldContext();
  const id = createUniqueId();
  onMount(() => ctx.setErrorMessageId(id));
  onCleanup(() => ctx.setErrorMessageId(undefined));
  return (
    <Show when={ctx.invalid()}>
      <p id={id} aria-live="polite" {...rest}>
        {local.children}
      </p>
    </Show>
  );
}
