/**
 * The anchors of the reply dropdowns on a thread, and the click-outside test
 * built on them.
 *
 * One map serves the whole screen: the reply being viewed and every reply under
 * it share a single "which menu is open" slot, so the handler has to know about
 * all of their anchors at once.
 */

/** Anchor element per dropdown key, e.g. `reply-42`. */
export type DropdownRefMap = Record<string, HTMLElement | null>;

/**
 * Records (or forgets) the element a dropdown hangs off.
 *
 * Unmounting deletes the entry rather than storing `null`. A `null` left in the
 * map makes `isClickOutsideDropdowns` answer "inside" for every click, because
 * the test has to treat an entry it cannot measure as unknown — so the open
 * menu would stop closing once any sibling anchor had come and gone.
 */
export function setDropdownRef(
  map: DropdownRefMap,
  key: string,
  element: HTMLElement | null
): void {
  if (element) {
    map[key] = element;
  } else {
    delete map[key];
  }
}

/**
 * True when the click landed outside every anchor currently in the map, which
 * is when the open menu should close.
 *
 * With no anchors at all there is nothing to be inside of, so the answer is
 * "outside" — closing is then a no-op, since nothing is open.
 */
export function isClickOutsideDropdowns(
  map: DropdownRefMap,
  target: Node | null
): boolean {
  return Object.values(map).every(
    (element) => !!element && !!target && !element.contains(target)
  );
}
