/**
 * Scroll the first field Formik rejected into view.
 *
 * The three publish forms — volunteering, development and events — each had
 * their own copy of this, identical line for line apart from the selector map.
 * The behaviour is the same in all three and the *rules* are not: only which
 * fields need a hand-written selector differs, so that is the parameter.
 *
 * Why a selector map is needed at all: most inputs can be found by
 * `[name="…"]`, but a rich text editor, a tag checkbox grid, a file dropzone
 * and the schedule picker render no input carrying the field's name. Those get
 * an explicit class or id.
 */
export type ErrorFieldSelectors = Record<string, string>;

/**
 * Finds the first erroring field and scrolls to it, falling back to the top of
 * the form when none of them can be located — which is better than leaving the
 * user on an apparently unresponsive Submit.
 *
 * `errors` is Formik's error object; it is deliberately loose because Formik
 * nests it to match the form's own shape, and only the top-level keys are used.
 */
export function scrollToFirstError(
  errors: Record<string, unknown> | undefined | null,
  specialFieldSelectors: ErrorFieldSelectors = {}
): void {
  if (!errors) return;
  const errorFields = Object.keys(errors);
  if (errorFields.length === 0) return;

  for (const fieldName of errorFields) {
    const element =
      document.querySelector(`[name="${fieldName}"]`) ??
      (specialFieldSelectors[fieldName]
        ? document.querySelector(specialFieldSelectors[fieldName])
        : null) ??
      document.getElementById(fieldName);

    if (element) {
      element.scrollIntoView({ behavior: "smooth", block: "center" });
      return;
    }
  }

  document
    .querySelector("form")
    ?.scrollIntoView({ behavior: "smooth", block: "start" });
}
