// packages/core/src/components/form/form-error-message.tsx
import type { JSX } from "solid-js";
import { Show, splitProps } from "solid-js";
import { useFormFieldContext } from "./form-context";
import type { FormErrorMessageProps } from "./form.props";

export type { FormErrorMessageProps };

/** Resolves children — either static JSX or a render-prop function. */
function resolveChildren(
  children: JSX.Element | ((errors: string[]) => JSX.Element),
  errors: string[],
): JSX.Element {
  if (typeof children === "function") {
    return (children as (e: string[]) => JSX.Element)(errors);
  }
  return children;
}

/**
 * Renders a <p role="alert"> with field error messages. Only mounts when
 * the field has at least one error. Supports static children or a render prop
 * receiving the errors array.
 */
export function FormErrorMessage(props: FormErrorMessageProps): JSX.Element {
  const [local, rest] = splitProps(props, ["children"]);
  const fieldCtx = useFormFieldContext();

  return (
    <Show when={fieldCtx.errors().length > 0}>
      <p id={fieldCtx.errorId} role="alert" {...rest}>
        {local.children !== undefined
          ? resolveChildren(local.children, fieldCtx.errors())
          : fieldCtx.errors().join(", ")}
      </p>
    </Show>
  );
}
