import InlineError from "./InlineError";
import classNames from 'classnames';
import { config } from "../config";
import { jsx as _jsx } from "preact/compat/jsx-runtime";
export const errorPlacementValues = ['top', 'bottom'];

// TODO: We should conditionally return an errorId, because we want to be able
// to include it in the aria-describedby without conditional logic in the component

/**
 * Hook that takes the props for a form field component, extracts the props relevant
 * to the error message, and conditionally renders an `InlineError` in the `topError`
 * or `bottomError` property based on the `errorPlacement` and the presence of an
 * `errorMessage`.
 */
export function useInlineError(props) {
  const errorId = props.errorId ?? `${props.id}__error`;
  const {
    errorMessage,
    errorMessageClassName,
    errorPlacement = config().errorPlacementDefault,
    inversed
  } = props;
  const errorElement = /*#__PURE__*/_jsx(InlineError, {
    id: errorId,
    inversed: inversed,
    className: classNames(errorMessageClassName, errorPlacement === 'bottom' && errorMessage && 'ds-c-inline-error--bottom'),
    children: errorMessage
  });
  let topError;
  let bottomError;
  if (errorPlacement === 'top') {
    topError = errorElement;
  } else {
    bottomError = errorElement;
  }

  // If the user has provided an `aria-invalid` attribute, use that as the source
  // of truth; otherwise, it's invalid if there's an error message.
  const invalid = props['aria-invalid'] ?? !!errorMessage;
  return {
    errorId: errorMessage ? errorId : undefined,
    invalid,
    topError,
    bottomError
  };
}