/**
 * Reading Formik's error and touched state for the repeatable social-link rows.
 *
 * `errors.socialMedia` is a union: a bare string when the whole array fails one
 * rule, or an array of per-row objects when individual rows fail. Both the
 * volunteer and the organization form were handling that with
 * `errors.socialMedia as any` followed by an inline `typeof !== "string"` check
 * repeated at three places each. These two helpers do the narrowing once, with
 * a real runtime check instead of a cast that silences one.
 */
import type { FormikErrors, FormikTouched } from "formik";

/** One social row, as both forms model it. */
export interface SocialMediaRow {
  platform: string;
  link: string;
}

/** Formik's error state for a `socialMedia` field, in all its shapes. */
export type SocialMediaErrors =
  | string
  | string[]
  | FormikErrors<SocialMediaRow>[]
  | undefined;

/** Formik's touched state for a `socialMedia` field. */
export type SocialMediaTouched = FormikTouched<SocialMediaRow>[] | undefined;

/**
 * The errors for one row, or `undefined`.
 *
 * Returns `undefined` for the whole-array string error too: that message is
 * rendered separately, not against a single row's inputs.
 */
export function socialRowError(
  errors: SocialMediaErrors,
  index: number
): FormikErrors<SocialMediaRow> | undefined {
  if (!Array.isArray(errors)) return undefined;
  const row: unknown = errors[index];
  return row !== null && typeof row === "object"
    ? (row as FormikErrors<SocialMediaRow>)
    : undefined;
}

/** Whether one row's field has been touched. */
export function socialRowTouched(
  touched: SocialMediaTouched,
  index: number
): FormikTouched<SocialMediaRow> | undefined {
  return Array.isArray(touched) ? touched[index] : undefined;
}
