/**
 * When scrolling to the bottom of a paged dropdown should fetch another page.
 *
 * Four menus in this app page their options: the sponsor picker on both publish
 * forms, the role picker on the volunteering registration, and the sponsor
 * picker on the event form. Each had written this check itself, and they did not
 * agree — which is the bug:
 *
 *  - only one of the four had a `page < total_pages` guard, so the other three
 *    kept incrementing the page at the bottom of the list and fired a request
 *    per scroll that could only come back empty;
 *  - two used an exact `scrollHeight - scrollTop === clientHeight`, which on a
 *    fractional device pixel ratio is never true, so the menu silently stops
 *    paging and the options simply end.
 *
 * One function, so all four behave the same way and the reasoning is in one
 * place.
 */

export interface MenuPagination {
  page: number;
  total_pages: number;
}

/** The scroll geometry the handler reads off the open menu. */
export interface MenuScrollGeometry {
  scrollTop: number;
  clientHeight: number;
  scrollHeight: number;
}

/**
 * Tolerance rather than equality: the three numbers are fractional on any
 * non-integer device pixel ratio, and an exact comparison then never matches.
 */
export const MENU_SCROLL_TOLERANCE_PX = 10;

export function shouldLoadNextMenuPage({
  geometry,
  isLoading,
  pagination,
}: {
  geometry: MenuScrollGeometry;
  isLoading: boolean;
  /** Absent means "there may be more" — which is what the first request needs. */
  pagination: MenuPagination | undefined;
}): boolean {
  const atBottom =
    geometry.scrollTop + geometry.clientHeight >=
    geometry.scrollHeight - MENU_SCROLL_TOLERANCE_PX;
  const hasMorePages = pagination
    ? pagination.page < pagination.total_pages
    : true;
  return atBottom && !isLoading && hasMorePages;
}

/** Reads the geometry off a scroll event and answers the same question. */
export function shouldLoadNextMenuPageFromEvent(
  event: { target: EventTarget | null },
  isLoading: boolean,
  pagination: MenuPagination | undefined
): boolean {
  const target = event.target as HTMLDivElement;
  return shouldLoadNextMenuPage({
    geometry: {
      scrollTop: target.scrollTop,
      clientHeight: target.clientHeight,
      scrollHeight: target.scrollHeight,
    },
    isLoading,
    pagination,
  });
}
