/**
 * The sponsor picker's merge rule.
 *
 * The paging decision moved to `features/shared/menuPaging.ts` once a third and
 * fourth copy of it turned up — in the volunteering role picker and the event
 * form's own sponsor picker, both without the last-page guard. It is re-exported
 * here under its old names so the existing call sites and tests keep working.
 */
import {
  MENU_SCROLL_TOLERANCE_PX,
  shouldLoadNextMenuPage,
  type MenuPagination,
  type MenuScrollGeometry,
} from "@/features/shared/menuPaging";

export type SponsorPagination = MenuPagination;
export type { MenuScrollGeometry };
export const SPONSOR_SCROLL_TOLERANCE_PX = MENU_SCROLL_TOLERANCE_PX;
export const shouldLoadNextSponsorPage = shouldLoadNextMenuPage;

export interface SponsorOption {
  label: string;
  value: string;
}

interface SponsorRecord {
  id: string;
  full_name: string | null;
}

/**
 * One de-duplicated option list from the attached sponsors and the scrolled
 * pages.
 *
 * First writer wins, and the attached sponsors are written first: their label
 * came with the opportunity and is the one the organizer chose. Letting the
 * later list win instead relabels a current selection the moment its page
 * loads, which is what a naive rewrite of this did.
 */
export function mergeSponsorOptions(
  preLoadedSponsors: SponsorRecord[],
  sponsorList: SponsorRecord[]
): SponsorOption[] {
  const byId = new Map<string, SponsorOption>();
  for (const sponsor of [...preLoadedSponsors, ...sponsorList]) {
    // The directory can return null/blank company names. Do not render an
    // empty option or let it hide a later named record with the same id.
    const label = sponsor.full_name?.trim();
    if (!label) continue;
    if (!byId.has(sponsor.id)) {
      byId.set(sponsor.id, { label, value: sponsor.id });
    }
  }
  return [...byId.values()];
}
