type ResizeDirection = {
  ns: "n" | "s" | "";
  ew: "e" | "w" | "";
  type: "square" | "roundResize" | "roundReshape" | "bench";
};
const minDiameter = boxSize * 2.5;

const getResizeDirection = (el: JQuery<HTMLElement>): ResizeDirection => {
  let ns: "n" | "s" | "" = "";
  let ew: "e" | "w" | "" = "";
  if (
    el.hasClass("topBorderResize") ||
    el.hasClass("topLeftResize") ||
    el.hasClass("topRightResize")
  )
    ns = "n";
  if (
    el.hasClass("bottomBorderResize") ||
    el.hasClass("bottomLeftResize") ||
    el.hasClass("bottomRightResize")
  )
    ns = "s";
  if (
    el.hasClass("rightBorderResize") ||
    el.hasClass("topRightResize") ||
    el.hasClass("bottomRightResize")
  )
    ew = "e";
  if (
    el.hasClass("leftBorderResize") ||
    el.hasClass("topLeftResize") ||
    el.hasClass("bottomLeftResize")
  )
    ew = "w";
  if (ns !== "" || ew !== "") return { ns, ew, type: "square" };

  if (el.hasClass("roundResize")) return { ns: "", ew: "", type: "roundResize" };
  if (el.hasClass("roundReshape")) return { ns: "", ew: "e", type: "roundReshape" };

  if (el.hasClass("leftBenchResize")) return { ns: "", ew: "w", type: "bench" };
  if (el.hasClass("rightBenchResize")) return { ns: "", ew: "e", type: "bench" };

  return { ns: "", ew: "", type: "square" };
};

$(() => {
  $("#addTableTools").on("mouseover", function () {
    const height = $("#tableTools").outerHeight() ?? 0;
    $("#tableToolsContainer").css("box-shadow", "0px 4px 16px 2px #0001");
    $("#tableToolsContainer").css("height", height + "px");
  });
  // Delegated from #room (never recreated) rather than bound directly to #canvas
  // (recreated by clearRoomCanvasDom on every room switch, which would drop a
  // direct binding along with the old canvas element).
  $("#room").on("mouseover", "#canvas", function () {
    closeTools();
  });

  $("#room").on("mousedown", "#canvas", function (e) {
    moveRoom = true;
    viewportMouseDownX = e.clientX;
    viewportMouseDownY = e.clientY;
    startRoomScrollLeft = roomScrollable.scrollLeft;
    startRoomScrollTop = roomScrollable.scrollTop;
    $(this).css("cursor", "grabbing");
    closeTools();

    if (roomMode === "preferenceMode") return;
    unselectAllTables();
    unselectAllGuests();
  });

  // The add-table buttons hand the new table straight to the drag logic
  // (withGrab), so the click's record covers the drop position too.
  $("#addSquareTableButton").on("click", function (e) {
    recordHistory();
    const { x, y } = mouseSpaceToRoomSpace(e.clientX, e.clientY);
    roomMouseDownX = x;
    roomMouseDownY = y;
    resizeStartCenterX = x;
    resizeStartCenterY = y;
    addSquareTable({ centerX: x, centerY: y, withGrab: true, addDefaultChairs: true });
    closeTools();
    if (roomMode === "preferenceMode") setRoomMode("buildMode");
  });
  $("#addRectangleTableButton").on("click", function (e) {
    recordHistory();
    const { x, y } = mouseSpaceToRoomSpace(e.clientX, e.clientY);
    roomMouseDownX = x;
    roomMouseDownY = y;
    resizeStartCenterX = x;
    resizeStartCenterY = y;
    addRectangleTable(x, y, true);
    closeTools();
    if (roomMode === "preferenceMode") setRoomMode("buildMode");
  });
  $("#addRoundTableButton").on("click", function (e) {
    recordHistory();
    const { x, y } = mouseSpaceToRoomSpace(e.clientX, e.clientY);
    roomMouseDownX = x;
    roomMouseDownY = y;
    resizeStartCenterX = x;
    resizeStartCenterY = y;
    addRoundTable({ centerX: x, centerY: y, withGrab: true, addDefaultChairs: true });
    closeTools();
    if (roomMode === "preferenceMode") setRoomMode("buildMode");
  });
  $("#addOvalTableButton").on("click", function (e) {
    recordHistory();
    const { x, y } = mouseSpaceToRoomSpace(e.clientX, e.clientY);
    roomMouseDownX = x;
    roomMouseDownY = y;
    resizeStartCenterX = x;
    resizeStartCenterY = y;
    addOvalTable(x, y, true);
    closeTools();
    if (roomMode === "preferenceMode") setRoomMode("buildMode");
  });
  $("#addBenchTableButton").on("click", function (e) {
    recordHistory();
    const { x, y } = mouseSpaceToRoomSpace(e.clientX, e.clientY);
    roomMouseDownX = x;
    roomMouseDownY = y;
    resizeStartCenterX = x;
    resizeStartCenterY = y;
    addBenchTable({ centerX: x, centerY: y, withGrab: true, addDefaultChairs: true });
    closeTools();
    if (roomMode === "preferenceMode") setRoomMode("buildMode");
  });

  $("#zoomInButton").on("mousedown", keepZoomIn);
  $("#zoomInButton").on("mouseup", stopZooming);
  $("#zoomOutButton").on("mousedown", keepZoomOut);
  $("#zoomOutButton").on("mouseup", stopZooming);

  $("#buildModeButton").on("click", function () {
    setRoomMode("buildMode");
    unselectAllGuests();
    unselectAllTables();
    updateAllGuestList();
    updateAllTablesInfo();
  });
  $("#placementModeButton").on("click", function () {
    setRoomMode("placementMode");
    unselectAllGuests();
    unselectAllTables();
    updateAllGuestList();
    updateAllTablesInfo();
  });

  // In preference mode a click on the table itself colours every chair at
  // once. Chair clicks bubble up through the table and are skipped here;
  // toggleChair on the chair already handled them.
  $("#room").on("click", ".table", function (e) {
    if (roomMode !== "preferenceMode") return;
    if ($(e.target).closest(".chair").length > 0) return;
    const tableId = $(this).attr("id") as TableId | undefined;
    if (!tableId) return;
    recordHistory();
    cycleTablePreference(tableId);
  });

  $("#room").on("mousedown", ".moveHandle", function (e) {
    if (!!guestBallSelector || !!draggableSelector) return;
    if (roomMode === "preferenceMode") return;
    // Only the main button: a right click opens the context menu, which
    // takes the mouseup with it, and a gesture begun would never end.
    if (e.button !== 0) return;
    const tableId = $(this).parent().attr("id") as TableId | undefined;
    if (!tableId) return;
    // Modifier state comes from the event itself, never from a tracked
    // keydown/keyup flag: a keyup lost to Cmd+Tab would leave such a flag
    // stuck and turn every plain click into a toggle.
    const toggling = e.shiftKey || e.metaKey;
    const alreadySelected = isSelectedTable(tableId);
    // What this press drags: the selection (with this table added when
    // toggling it in), or this table alone — nothing when toggling it out.
    // Refused while someone else has one of them in hand (presence.ts).
    const dragged =
      toggling && alreadySelected
        ? []
        : alreadySelected
          ? selectedTables.map((t) => t.tableId)
          : [...(toggling ? selectedTables.map((t) => t.tableId) : []), tableId];
    if (!claimOrRefuse("table", dragged)) return;
    // Drags record at mousedown (state before the gesture) and commit at
    // the #body mouseup below — one undo step per move/resize/rotate.
    recordHistory();
    draggableSelector = $(this).parent();
    const { x, y } = mouseSpaceToRoomSpace(e.clientX, e.clientY);
    roomMouseDownX = x;
    roomMouseDownY = y;
    closeTools();
    $("body").addClass("unselectableText");

    if (toggling && alreadySelected) {
      unselectOneTable(tableId);
      draggableSelector = undefined;
    } else if (toggling) {
      selectTables([tableId]);
    } else if (!alreadySelected) {
      selectOneTable(tableId);
    }
  });

  $("#room").on("mousedown", ".resizeHandle", function (e) {
    if (!!guestBallSelector) return;
    if (roomMode === "preferenceMode") return;
    if (e.button !== 0) return;
    const tableId = $(this).parent().attr("id") as TableId | undefined;
    if (!tableId) return;
    if (!claimOrRefuse("table", [tableId])) return;
    recordHistory();
    resizeSelector = $(this).parent();
    const { x, y } = mouseSpaceToRoomSpace(e.clientX, e.clientY);
    roomMouseDownX = x;
    roomMouseDownY = y;
    startWidth = resizeSelector.width() ?? 0;
    startHeight = resizeSelector.height() ?? 0;
    resizeStartCenterX = parseInt(resizeSelector.css("left"));
    resizeStartCenterY = parseInt(resizeSelector.css("top"));
    startRotation = getRotation(tableId);
    endTranslateX = 0;
    endTranslateY = 0;
    activeResize = getResizeDirection($(this));
    // Set here, not only in the .resizeHandle mouseover: the round-table resize
    // math pivots on it every move, and touch grabs never hover first.
    const center = getElementCenter(tableId);
    dragPivotX = center.x;
    dragPivotY = center.y;

    const vector1 = { x: 1, y: 0 };
    const vector2 = { x: x - dragPivotX, y: y - dragPivotY };
    const newRotation = getAngle(vector1, vector2, 0);
    startRadius = getProjection(x - dragPivotX, y - dragPivotY, newRotation);

    showResizeCursor();
    if (!isSelectedTable(tableId)) selectOneTable(tableId);
    closeTools();
    $("body").addClass("unselectableText");
  });

  $("#room").on("mousedown", ".rotateHandle", function (e) {
    if (!!guestBallSelector) return;
    if (roomMode === "preferenceMode") return;
    if (e.button !== 0) return;
    const tableId = $(this).parent().attr("id") as TableId | undefined;
    if (!tableId) return;
    if (!claimOrRefuse("table", [tableId])) return;
    recordHistory();
    rotateSelector = $(this).parent();
    const { x, y } = mouseSpaceToRoomSpace(e.clientX, e.clientY);
    roomMouseDownX = x;
    roomMouseDownY = y;
    startRotation = getRotation(tableId);
    const center = getElementCenter(tableId);
    dragPivotX = center.x;
    dragPivotY = center.y;
    showRotateCursor();
    if (!isSelectedTable(tableId)) selectOneTable(tableId);
    closeTools();
    $("body").addClass("unselectableText");
  });

  $("#room").on("mouseover", ".resizeHandle", function () {
    if (!!rotateSelector || !!resizeSelector || !!guestBallSelector) return;
    if (roomMode === "preferenceMode") return;
    const id = $(this).parent().attr("id");
    if (!id) return;
    startRotation = getRotation(id);
    activeResize = getResizeDirection($(this));
    const center = getElementCenter(id);
    dragPivotX = center.x;
    dragPivotY = center.y;
    startWidth = $(this).parent().width() ?? 0;
    startHeight = $(this).parent().height() ?? 0;
    showResizeCursor();
  });

  $("#room").on("mousemove", ".resizeHandle", function () {
    if (roomMode === "preferenceMode") return;
    showResizeCursor();
  });
  $("#room").on("mouseout", ".resizeHandle", function () {
    hideCustomCursor();
  });

  $("#room").on("mouseover", ".rotateHandle", function () {
    if (!!rotateSelector || !!resizeSelector || guestBallSelector) return;
    if (roomMode === "preferenceMode") return;
    const id = $(this).parent().attr("id");
    if (!id) return;
    const center = getElementCenter(id);
    dragPivotX = center.x;
    dragPivotY = center.y;
    showRotateCursor();
  });

  $("#room").on("mousemove", ".rotateHandle", function () {
    if (roomMode === "preferenceMode") return;
    showRotateCursor();
  });
  $("#room").on("mouseout", ".rotateHandle", function () {
    hideCustomCursor();
  });

  $("#room").on("mouseover", ".moveHandle", function () {
    if (roomMode === "preferenceMode") return;
    showMoveCursor();
  });
  $("#room").on("mousemove", ".moveHandle", function () {
    if (roomMode === "preferenceMode") return;
    showMoveCursor();
  });
  $("#room").on("mouseout", ".moveHandle", function () {
    hideCustomCursor();
  });

  $(window).on("scroll", function () {
    moveCustomCursor();

    roomScrollableRect = roomScrollable.getBoundingClientRect();
  });

  $(window).on("resize", function () {
    roomScrollableRect = roomScrollable.getBoundingClientRect();
    updateCurrentScale(clampZoom(currentScale));
    applyRoomScale();
  });

  // Grabbing a guest row (anywhere but its ball and icon buttons) behaves like
  // grabbing its ball, but only once the pointer has travelled a few pixels: a
  // plain click on a row must stay a click (select, no undo step, no ball).
  const ROW_GRAB_SLOP_PX = 5;
  let pendingRowGrab: { guestId: GuestId; x: number; y: number } | undefined = undefined;

  // The ball has its own mousedown that stops propagation, so only presses on
  // the rest of the row get here.
  $("#allGuests").on("mousedown", ".guestRow", function (e) {
    if (e.button !== 0 || $(e.target).closest(".rowIconButton").length > 0) return;
    pendingRowGrab = { guestId: this.id as GuestId, x: e.clientX, y: e.clientY };
    $("body").addClass("unselectableText");
  });

  $("#body").on("mousemove", function (e) {
    if (!pendingRowGrab) return;
    if (Math.hypot(e.clientX - pendingRowGrab.x, e.clientY - pendingRowGrab.y) < ROW_GRAB_SLOP_PX) {
      return;
    }
    const { guestId } = pendingRowGrab;
    pendingRowGrab = undefined;
    grabBall(e.originalEvent as MouseEvent, guestId, "List");
  });

  $("#body").on("mouseup", function () {
    if (!pendingRowGrab) return;
    pendingRowGrab = undefined;
    $("body").removeClass("unselectableText");
  });

  $("#body").on("mousemove", function (e) {
    viewportMouseX = e.clientX;
    viewportMouseY = e.clientY;

    const { x, y } = mouseSpaceToRoomSpace(e.clientX, e.clientY);
    const mouseMoveX = x;
    const mouseMoveY = y;
    const roomMouseDiffX = mouseMoveX - roomMouseDownX;
    const roomMouseDiffY = mouseMoveY - roomMouseDownY;

    updateCursor(x, y);

    if (moveRoom) {
      const viewportMouseDiffX = viewportMouseX - viewportMouseDownX;
      const viewportMouseDiffY = viewportMouseY - viewportMouseDownY;
      roomScrollable.scrollLeft = startRoomScrollLeft - viewportMouseDiffX;
      roomScrollable.scrollTop = startRoomScrollTop - viewportMouseDiffY;
    } else if (!!rotateSelector) {
      showRotateCursor();
      const tableId = rotateSelector.attr("id") as TableId | undefined;
      if (!tableId) return;
      const vector1 = { x: roomMouseDownX - dragPivotX, y: roomMouseDownY - dragPivotY };
      const vector2 = { x: mouseMoveX - dragPivotX, y: mouseMoveY - dragPivotY };
      const newRotation = getAngle(vector1, vector2, startRotation, snapTablesToGrid);
      rotateSelector.css("transform", rotateTransform(newRotation));
      $("#" + tableId + " .adjustRotation").css("transform", rotateTransform(-newRotation));
    } else if (!!resizeSelector) {
      showResizeCursor();
      endTranslateX = 0;
      endTranslateY = 0;
      const tableId = resizeSelector.attr("id") as TableId | undefined;
      if (!tableId) return;

      let chairsToggled = false;

      if (activeResize.type === "square" || activeResize.type === "bench") {
        const isBench = activeResize.type === "bench";

        if (activeResize.ns !== "") {
          const rot = activeResize.ns === "n" ? 270 : 90;
          const mouseMovement = getProjection(roomMouseDiffX, roomMouseDiffY, startRotation + rot);
          const mouseMovementMagnet = Math.max(
            magnetizeValue(mouseMovement, 2 * boxSize),
            -startHeight + boxSize,
          );
          const newHeight = startHeight + mouseMovementMagnet;
          if (activeResize.ns === "n") endTranslateY = -mouseMovementMagnet / 2;
          if (activeResize.ns === "s") endTranslateY = mouseMovementMagnet / 2;

          resizeSelector.css("height", newHeight + "px");
          $("#" + tableId + " .bottomChair").each((i, e) => {
            $(e).css("top", startHeight + GAP_CHAIR_TABLE + mouseMovementMagnet + "px");
          });

          const prevNrOfChairsY = chairCount(startHeight);
          const nrOfNewChairsY = chairCount(newHeight);

          if (activeResize.ns === "n") {
            for (let y = 0; y > prevNrOfChairsY - nrOfNewChairsY; y--) {
              const chairId = getChairId(tableId, "left", y);
              if (allChairSpots[chairId] === undefined) {
                addChairSpot(tableId, "left", y);
                addChairSpot(tableId, "right", y);
              }
            }
            $("#" + tableId + " .rightChair, #" + tableId + " .leftChair").each((i, e) => {
              const chairId = $(e).attr("id") as ChairId | undefined;
              if (!chairId) return;
              const chairSpot = allChairSpots[chairId];
              if (!chairSpot) return;
              const { chairNr, chairType } = chairSpot;
              if (chairNr <= prevNrOfChairsY - nrOfNewChairsY) {
                chairsToggled = hideChair(chairId) || chairsToggled;
              } else {
                chairsToggled = showChair(chairId) || chairsToggled;
                const top =
                  getChairPosition(startWidth, newHeight, chairType, chairNr).top +
                  mouseMovementMagnet;
                $(e).css("top", top + "px");
              }
            });
          } else {
            for (let y = prevNrOfChairsY; y <= nrOfNewChairsY; y++) {
              const chairId = getChairId(tableId, "left", y);
              if (allChairSpots[chairId] === undefined) {
                addChairSpot(tableId, "left", y);
                addChairSpot(tableId, "right", y);
              }
            }
            $("#" + tableId + " .rightChair, #" + tableId + " .leftChair").each((i, e) => {
              const chairId = $(e).attr("id") as ChairId | undefined;
              if (!chairId) return;
              const chairSpot = allChairSpots[chairId];
              if (!chairSpot) return;
              if (chairSpot.chairNr > nrOfNewChairsY) {
                chairsToggled = hideChair(chairId) || chairsToggled;
              } else {
                chairsToggled = showChair(chairId) || chairsToggled;
              }
            });
          }
        }

        if (activeResize.ew !== "") {
          const rot = activeResize.ew === "w" ? 180 : 0;
          const mouseMovement = getProjection(roomMouseDiffX, roomMouseDiffY, startRotation + rot);
          const mouseMovementMagnet = Math.max(
            magnetizeValue(mouseMovement, 2 * boxSize),
            -startWidth + boxSize,
          );
          const newWidth = startWidth + mouseMovementMagnet;
          if (activeResize.ew === "w") endTranslateX = -mouseMovementMagnet / 2;
          if (activeResize.ew === "e") endTranslateX = mouseMovementMagnet / 2;

          resizeSelector.css("width", newWidth + "px");
          $("#" + tableId + " .rightChair").each((i, e) => {
            $(e).css("left", startWidth + GAP_CHAIR_TABLE + mouseMovementMagnet + "px");
          });

          const prevNrOfChairsX = chairCount(startWidth);
          const nrOfNewChairsX = chairCount(newWidth);

          if (activeResize.ew === "w") {
            for (let x = 0; x > prevNrOfChairsX - nrOfNewChairsX; x--) {
              const chairId = getChairId(tableId, "top", x);
              if (allChairSpots[chairId] === undefined) {
                addChairSpot(tableId, "top", x);
                if (!isBench) addChairSpot(tableId, "bottom", x);
              }
            }
            $("#" + tableId + " .topChair, #" + tableId + " .bottomChair").each((i, e) => {
              const chairId = $(e).attr("id") as ChairId | undefined;
              if (!chairId) return;
              const chairSpot = allChairSpots[chairId];
              if (!chairSpot) return;
              const { chairNr, chairType } = chairSpot;
              if (chairNr <= prevNrOfChairsX - nrOfNewChairsX) {
                chairsToggled = hideChair(chairId) || chairsToggled;
              } else {
                chairsToggled = showChair(chairId) || chairsToggled;
                const left =
                  getChairPosition(newWidth, startHeight, chairType, chairNr).left +
                  mouseMovementMagnet;
                $(e).css("left", left + "px");
              }
            });
          } else {
            for (let x = prevNrOfChairsX; x <= nrOfNewChairsX; x++) {
              const chairId = getChairId(tableId, "top", x);
              if (allChairSpots[chairId] === undefined) {
                addChairSpot(tableId, "top", x);
                if (!isBench) addChairSpot(tableId, "bottom", x);
              }
            }
            $("#" + tableId + " .topChair, #" + tableId + " .bottomChair").each((i, e) => {
              const chairId = $(e).attr("id") as ChairId | undefined;
              if (!chairId) return;
              const chairSpot = allChairSpots[chairId];
              if (!chairSpot) return;
              if (chairSpot.chairNr > nrOfNewChairsX) {
                chairsToggled = hideChair(chairId) || chairsToggled;
              } else {
                chairsToggled = showChair(chairId) || chairsToggled;
              }
            });
          }
        }

        if (activeResize.ns !== "" || activeResize.ew !== "") {
          resizeSelector.css(
            "transform",
            rotateTransform(startRotation, endTranslateX, endTranslateY),
          );
        }
      }

      if (activeResize.type === "roundReshape") {
        const rot =
          activeResize.ns === "n"
            ? 270
            : activeResize.ew === "w"
              ? 180
              : activeResize.ns === "s"
                ? 90
                : 0;

        const circumference = ellipseCircumference(startHeight / 2, startWidth / 2);
        const mouseMovement = getProjection(roomMouseDiffX, roomMouseDiffY, startRotation + rot);

        let newHeight = 0;
        let newWidth = 0;
        if (activeResize.ns !== "") {
          newHeight = Math.max(startHeight + mouseMovement * 2, minDiameter);
          newWidth = getOtherRadius(circumference, newHeight / 2) * 2;
          if (isNaN(newWidth) || newWidth < minDiameter) {
            newWidth = minDiameter;
            newHeight = getOtherRadius(circumference, newWidth / 2) * 2;
          }
        }
        if (activeResize.ew !== "") {
          newWidth = Math.max(startWidth + mouseMovement * 2, minDiameter);
          newHeight = getOtherRadius(circumference, newWidth / 2) * 2;
          if (isNaN(newHeight) || newHeight < minDiameter) {
            newHeight = minDiameter;
            newWidth = getOtherRadius(circumference, newHeight / 2) * 2;
          }
        }

        const ratio = newHeight / newWidth;
        if (ratio > 0.85 && ratio < 1.15) {
          newWidth = (newWidth + newHeight) / 2;
          newHeight = newWidth;
        }

        resizeSelector.css("height", newHeight + "px");
        resizeSelector.css("width", newWidth + "px");

        const roundReshapeSamplePoints = getRoundTableSamplePoints(newWidth, newHeight);
        $("#" + tableId + " .roundChair").each((i, e) => {
          const chairId = $(e).attr("id") as ChairId | undefined;
          if (!chairId) return;
          const chairSpot = allChairSpots[chairId];
          if (!chairSpot) return;
          const { chairNr } = chairSpot;
          const { left, top } = getChairPosition(
            newWidth,
            newHeight,
            "round",
            chairNr,
            roundReshapeSamplePoints,
          );
          $(e).css("top", top + "px");
          $(e).css("left", left + "px");
        });
      }

      if (activeResize.type === "roundResize") {
        const R = startRotation * DEG_TO_RAD;
        const { x, y } = rotateXY(mouseMoveX - dragPivotX, mouseMoveY - dragPivotY, -R);
        const ratio = startHeight / startWidth;
        // Semi-width of the fixed-aspect ellipse that passes through (x, y):
        // solving x²/a² + y²/(ratio·a)² = 1 for a. No trig, no x=0 singularity.
        const a = Math.sqrt(x * x + (y / ratio) * (y / ratio));
        const b = ratio * a;
        const newWidth = a * 2;
        const newHeight = b * 2;

        resizeSelector.css("height", newHeight + "px");
        resizeSelector.css("width", newWidth + "px");

        const startCircumference = ellipseCircumference(startWidth / 2, startHeight / 2);
        const newCircumference = ellipseCircumference(newWidth / 2, newHeight / 2);
        const prevNrOfChairs = Math.round(startCircumference / arcLenghtBetween2Chairs);
        const nrOfNewChairs = Math.round(newCircumference / arcLenghtBetween2Chairs);
        for (let r = prevNrOfChairs; r <= nrOfNewChairs; r++) {
          const chairId = getChairId(tableId, "round", r);
          if (allChairSpots[chairId] === undefined) addChairSpot(tableId, "round", r);
        }
        const roundResizeSamplePoints = getRoundTableSamplePoints(newWidth, newHeight);
        $("#" + tableId + " .roundChair").each((i, e) => {
          const chairId = $(e).attr("id") as ChairId | undefined;
          if (!chairId) return;
          const chairSpot = allChairSpots[chairId];
          if (!chairSpot) return;
          const { chairNr } = chairSpot;
          const { left, top } = getChairPosition(
            newWidth,
            newHeight,
            "round",
            chairNr,
            roundResizeSamplePoints,
          );
          $(e).css("top", top + "px");
          $(e).css("left", left + "px");
          if (chairNr > nrOfNewChairs) $(e).hide();
          else $(e).show();
        });
      }

      if (chairsToggled) updateDisplayNumbers(tableId);
    } else if (!!draggableSelector) {
      showMoveCursor();
      for (let selectedTable of selectedTables) {
        const { tableId, startCenterY, startCenterX, startRotation } = selectedTable;
        const moveX = snapTablesToGrid ? magnetizeValue(roomMouseDiffX, boxSize) : roomMouseDiffX;
        const moveY = snapTablesToGrid ? magnetizeValue(roomMouseDiffY, boxSize) : roomMouseDiffY;
        const newLeft = Math.min(Math.max(startCenterX + moveX, 0), BASE_ROOM_SIZE);
        const newTop = Math.min(Math.max(startCenterY + moveY, 0), BASE_ROOM_SIZE);
        // translateX/Y inside rotate() are applied in the table's own rotated axes,
        // so pre-rotate the desired screen-space offset by -rotation to cancel that out.
        const R = startRotation * DEG_TO_RAD;
        const { x: tx, y: ty } = rotateXY(newLeft - startCenterX, newTop - startCenterY, -R);
        $("#" + tableId).css("transform", rotateTransform(startRotation, tx, ty));
      }
    } else if (!!guestBallSelector) {
      const dx = viewportMouseX + window.scrollX - guestBallGrabX;
      const dy = viewportMouseY + window.scrollY - guestBallGrabY;
      guestBallSelector.css(
        "transform",
        `translate3d(${dx}px, ${dy}px, 0) scale(${guestBallGrabScale})`,
      );
    } else if (!!rowSelector) {
      updateRowDragState();
      if (guestListAutoScrollFrame === undefined) {
        guestListAutoScrollFrame = requestAnimationFrame(stepGuestListAutoScroll);
      }
    }
    // The gesture as it stands, to the others (presence.ts).
    presenceReportDrag();
  });
  let startNewGroupTimer: number;
  let startNewGroupTimerStarted = false;
  let startNewGroupGuestId: GuestId | undefined;
  let startNewGroupPlace: "above" | "below" = "below";

  const guestListAutoScrollEdgeZone = 60;
  const guestListAutoScrollMaxSpeed = 14;
  const headerHeight = 64;
  let guestListAutoScrollFrame: number | undefined = undefined;

  function stepGuestListAutoScroll() {
    if (!rowSelector) {
      guestListAutoScrollFrame = undefined;
      return;
    }

    const container = document.querySelector("#stepPanel .scrollContainer") as HTMLElement | null;
    if (container) {
      const rect = container.getBoundingClientRect();
      let speed = 0;
      if (viewportMouseY < rect.top + headerHeight + guestListAutoScrollEdgeZone) {
        const proximity =
          (rect.top + headerHeight + guestListAutoScrollEdgeZone - viewportMouseY) /
          guestListAutoScrollEdgeZone;
        speed = -guestListAutoScrollMaxSpeed * Math.min(1, Math.max(0, proximity));
      } else if (viewportMouseY > rect.bottom - guestListAutoScrollEdgeZone) {
        const proximity =
          (viewportMouseY - (rect.bottom - guestListAutoScrollEdgeZone)) /
          guestListAutoScrollEdgeZone;
        speed = guestListAutoScrollMaxSpeed * Math.min(1, Math.max(0, proximity));
      }

      if (speed !== 0) {
        container.scrollTop += speed;
        updateRowDragState();
      }
    }

    guestListAutoScrollFrame = requestAnimationFrame(stepGuestListAutoScroll);
  }

  function updateRowDragState() {
    if (!rowSelector) return;

    const height = rowSelector.outerHeight() ?? 0;
    const top = viewportMouseY + window.scrollY - height / 2;
    rowSelector.css("top", top + "px");

    const list = document.getElementById("allGuests");
    if (list) guestListTop = list.getBoundingClientRect().top;
    const mouseListPosition = viewportMouseY - guestListTop;

    const midRowPositions = guestRowOffsets.map(
      (g, i) => g.top + g.height / 2 + (i >= newListIndex ? height + guestGap : 0),
    );

    newListIndex = midRowPositions.length;
    const diffs: number[] = [];
    for (let i = 0; i < midRowPositions.length; i++) {
      diffs.push(Math.abs(mouseListPosition - midRowPositions[i]));
      if (mouseListPosition < midRowPositions[i]) {
        newListIndex = i;
        break;
      }
    }
    $(".guestSpace").css("height", `${guestGap}px`);
    $(".guestSpaceHalf").css("height", `${guestGap / 2}px`);

    const isHalf = $(".guestSpace").eq(newListIndex).hasClass("guestSpaceHalf");

    $(".guestSpace")
      .eq(newListIndex)
      .css(
        "height",
        (startNewGroupGuestId
          ? groupStartHeight + 3 * guestGap + groupEndHeight
          : isHalf
            ? 1.5 * guestGap
            : guestGap * 2) +
          height +
          "px",
      );

    const diff = Math.min(...diffs);
    const hoverIndex = diffs.indexOf(diff);

    let flatI = 0;
    let hoverGuestId: GuestId | undefined = undefined;
    for (let i = 0; i < guestOrder.length; i++) {
      const entry = guestOrder[i];
      if (entry.isGroup) {
        flatI += allGroups[entry.groupId].guestIds.length + 2;
      } else {
        if (flatI++ === hoverIndex) {
          hoverGuestId = entry.guestId;
        }
      }
    }

    const isAbove = mouseListPosition < midRowPositions[hoverIndex];

    if (diff <= 23 && hoverGuestId) {
      if (!startNewGroupTimerStarted) {
        startNewGroupTimerStarted = true;
        startNewGroupTimer = setTimeout(() => {
          $("#newGroup_" + hoverGuestId + " .newGroupBorder").css("opacity", "1");
          $("#" + hoverGuestId).css("width", "calc(100% - 8px)");
          if (isAbove) {
            startNewGroupGuestId = hoverGuestId;
            startNewGroupPlace = "above";
            $("#newGroup_" + hoverGuestId).css("top", `-${guestGap / 2 + groupEndHeight}px`);
            $("#newGroup_" + hoverGuestId + " .newGroupBorder").css(
              "top",
              `-${height + guestGap * 1.5 + groupStartHeight / 2}px`,
            );
            $("#newGroup_" + hoverGuestId + " .newGroupBorder").css(
              "bottom",
              `-${guestGap / 2 + groupEndHeight}px`,
            );
          } else {
            startNewGroupGuestId = hoverGuestId;
            startNewGroupPlace = "below";
            $("#newGroup_" + hoverGuestId).css("top", `${groupStartHeight + guestGap / 2}px`);
            $("#newGroup_" + hoverGuestId + " .newGroupBorder").css(
              "top",
              `-${groupStartHeight / 2 + guestGap / 2}px`,
            );
            $("#newGroup_" + hoverGuestId + " .newGroupBorder").css(
              "bottom",
              `-${height + guestGap * 1.5 + groupEndHeight}px`,
            );
          }
          $(`.guestSpace`)
            .eq(newListIndex)
            .css("height", groupStartHeight + 3 * guestGap + groupEndHeight + height + "px");
        }, 500);
      }
    } else if (
      hoverGuestId + (isAbove ? "above" : "below") !==
      startNewGroupGuestId + startNewGroupPlace
    ) {
      clearTimeout(startNewGroupTimer);
      startNewGroupTimerStarted = false;
      startNewGroupGuestId = undefined;
      $(".newGroup").css("top", "");
      $(".newGroupBorder").css("opacity", "0");
      $(".newGroupBorder").css("top", "-8px");
      $(".newGroupBorder").css("bottom", "-8px");
      $("#allGuests .guestRow").css("width", "");
    }
  }
  $("#body").on("mouseup", function () {
    let tableId: TableId | undefined = undefined;

    if (!!rotateSelector) {
      tableId = rotateSelector.attr("id") as TableId | undefined;
      if (!tableId) return;
      const endRotation = getRotation(tableId);
      if (snapTablesToGrid && endRotation % 90 === 0) snapToGrid(rotateSelector);
    } else if (!!resizeSelector && activeResize.type === "roundResize") {
      tableId = resizeSelector.attr("id") as TableId | undefined;
      if (!tableId) return;

      let height = resizeSelector.height() ?? 0;
      let width = resizeSelector.width() ?? 0;
      if (width < minDiameter || height < minDiameter) {
        if (width < height) {
          width = minDiameter;
          height = (width * startHeight) / startWidth;
        } else {
          height = minDiameter;
          width = (height * startWidth) / startHeight;
        }
      }
      const circumference = ellipseCircumference(height / 2, width / 2);
      const nrOfChairs = $("#" + tableId + " .roundChair").toArray().length;
      const nrOfNewChairs = Math.max(Math.round(circumference / arcLenghtBetween2Chairs), 4);
      const newCircumference = nrOfNewChairs * arcLenghtBetween2Chairs;

      let lowerGuessHeight = 0;
      let higherGuessHeight = 0;

      if (newCircumference < circumference) {
        lowerGuessHeight = height / 2;
        higherGuessHeight = height;
      } else {
        lowerGuessHeight = height;
        higherGuessHeight = height * 2;
      }

      let newHeight = (lowerGuessHeight + higherGuessHeight) / 2;
      let newWidth = (newHeight * width) / height;

      for (let i = 0; i < 12; i++) {
        const guessCircumference = ellipseCircumference(newHeight / 2, newWidth / 2);
        if (guessCircumference < newCircumference) lowerGuessHeight = newHeight;
        if (guessCircumference > newCircumference) higherGuessHeight = newHeight;
        newHeight = (lowerGuessHeight + higherGuessHeight) / 2;
        newWidth = (newHeight * width) / height;
      }

      resizeSelector.css("width", newWidth + "px");
      resizeSelector.css("height", newHeight + "px");

      if (nrOfNewChairs < nrOfChairs) {
        for (let r = nrOfChairs; r > nrOfNewChairs; r--) {
          const chairId = getChairId(tableId, "round", r);
          $("#" + chairId).remove();
          deleteChairSpot(chairId);
        }
      }

      const roundDiameterSamplePoints = getRoundTableSamplePoints(newWidth, newHeight);
      $("#" + tableId + " .roundChair").each((i, e) => {
        const chairId = $(e).attr("id") as ChairId | undefined;
        if (!chairId) return;
        const chairSpot = allChairSpots[chairId];
        if (!chairSpot) return;
        const { left, top } = getChairPosition(
          newWidth,
          newHeight,
          "round",
          chairSpot.chairNr,
          roundDiameterSamplePoints,
        );
        $(e).css("top", top + "px");
        $(e).css("left", left + "px");
      });

      $(".chair").show();
      updateDisplayNumbers(tableId);
      updateAllTablesInfo();
      updateAllGuestList();
      updatePlacementInfo();
    } else if (
      !!resizeSelector &&
      (activeResize.type === "square" || activeResize.type === "bench")
    ) {
      const isBench = activeResize.type === "bench";
      tableId = resizeSelector.attr("id") as TableId | undefined;
      if (!tableId) return;
      const boxSizeX2 = boxSize * 2;
      const newWidth = Math.max(
        Math.round(((resizeSelector.width() ?? 0) - boxSize) / boxSizeX2) * boxSizeX2 + boxSize,
        3 * boxSize,
      );
      const newHeight = isBench
        ? boxSize
        : Math.max(
            Math.round(((resizeSelector.height() ?? 0) - boxSize) / boxSizeX2) * boxSizeX2 +
              boxSize,
            3 * boxSize,
          );
      const mouseMovementX = newWidth - startWidth;
      const mouseMovementY = newHeight - startHeight;

      endTranslateX = 0;
      endTranslateY = 0;
      if (activeResize.ns === "n") endTranslateY = -mouseMovementY / 2;
      if (activeResize.ns === "s") endTranslateY = mouseMovementY / 2;
      if (activeResize.ew === "w") endTranslateX = -mouseMovementX / 2;
      if (activeResize.ew === "e") endTranslateX = mouseMovementX / 2;

      // Convert local-axis translation to screen-space and bake into top/left
      const R = startRotation * DEG_TO_RAD;
      const { x, y } = rotateXY(endTranslateX, endTranslateY, R);
      const newLeft = resizeStartCenterX + x;
      const newTop = resizeStartCenterY + y;

      resizeSelector.css("left", newLeft + "px");
      resizeSelector.css("top", newTop + "px");
      resizeSelector.css("width", newWidth + "px");
      resizeSelector.css("height", newHeight + "px");
      resizeSelector.css("transform", rotateTransform(startRotation));

      $("#" + tableId + " .bottomChair").each((i, e) => {
        $(e).css("top", newHeight + "px");
      });
      $("#" + tableId + " .rightChair").each((i, e) => {
        $(e).css("left", newWidth + "px");
      });

      if (activeResize.ns !== "") {
        const prevNrOfChairsY = chairCount(startHeight);
        const nrOfNewChairsY = chairCount(newHeight);

        if (activeResize.ns === "n") {
          const diff = nrOfNewChairsY - prevNrOfChairsY;
          const newChairSpots: { [chairId: ChairId]: ChairSpot } = {};
          const newPlacement: { [guestId: GuestId]: ChairId } = {};
          const chairIdRenames: { [oldChairId: ChairId]: ChairId } = {};
          let chairPairsToDelete = 0;
          $("#" + tableId + " .rightChair, #" + tableId + " .leftChair").each((i, e) => {
            const chairId = $(e).attr("id") as ChairId | undefined;
            if (!chairId) return;
            const chairSpot = allChairSpots[chairId];
            if (!chairSpot) return;
            const newChairNr = chairSpot.chairNr + diff;
            const newChairId = getChairId(tableId!, chairSpot.chairType, newChairNr);
            if (newChairNr < 1) {
              if (chairSpot.chairType === "left") chairPairsToDelete++;
              deleteChairSpot(chairId);
            } else {
              newChairSpots[newChairId] = {
                ...chairSpot,
                chairId: newChairId,
                chairNr: newChairNr,
              };
              const guestId = getGuestOnChair(chairId);
              if (guestId) newPlacement[guestId] = newChairId;
              removeChairFromPlacement(chairId);
              chairIdRenames[chairId] = newChairId;
              delete allChairSpots[chairId];
            }
            $(e).attr("id", newChairId);
            $(e).attr("onclick", "toggleChair('" + newChairId + "')");
          });
          for (let chairId of objectKeys(newChairSpots)) {
            allChairSpots[chairId] = newChairSpots[chairId];
          }
          for (let guestId of objectKeys(newPlacement)) {
            placement[guestId] = newPlacement[guestId];
          }
          applyChairIdRenames(chairIdRenames);
          updatePlacementInfo();
          for (let y = 0; y > -chairPairsToDelete; y--) {
            const leftId = getChairId(tableId, "left", y);
            const rightId = getChairId(tableId, "right", y);
            $("#" + leftId).remove();
            $("#" + rightId).remove();
            deleteChairSpot(leftId);
            deleteChairSpot(rightId);
          }
        } else {
          const nrOfChairs = $("#" + tableId + " .leftChair").toArray().length;
          if (nrOfNewChairsY < nrOfChairs) {
            for (let y = nrOfChairs; y > nrOfNewChairsY; y--) {
              const leftId = getChairId(tableId, "left", y);
              const rightId = getChairId(tableId, "right", y);
              $("#" + leftId).remove();
              $("#" + rightId).remove();
              deleteChairSpot(leftId);
              deleteChairSpot(rightId);
            }
          }
        }
      }

      if (activeResize.ew !== "") {
        const prevNrOfChairsX = chairCount(startWidth);
        const nrOfNewChairsX = chairCount(newWidth);

        if (activeResize.ew === "w") {
          const diff = nrOfNewChairsX - prevNrOfChairsX;
          const newChairSpots: { [chairId: ChairId]: ChairSpot } = {};
          const newPlacement: { [guestId: GuestId]: ChairId } = {};
          const chairIdRenames: { [oldChairId: ChairId]: ChairId } = {};
          let chairPairsToDelete = 0;
          $("#" + tableId + " .topChair, #" + tableId + " .bottomChair").each((i, e) => {
            const chairId = $(e).attr("id") as ChairId | undefined;
            if (!chairId) return;
            const chairSpot = allChairSpots[chairId];
            if (!chairSpot) return;
            const newChairNr = chairSpot.chairNr + diff;
            const newChairId = getChairId(tableId!, chairSpot.chairType, newChairNr);
            if (newChairNr < 1) {
              if (chairSpot.chairType === "top") chairPairsToDelete++;
              deleteChairSpot(chairId);
            } else {
              newChairSpots[newChairId] = {
                ...chairSpot,
                chairId: newChairId,
                chairNr: newChairNr,
              };
              const guestId = getGuestOnChair(chairId);
              if (guestId) newPlacement[guestId] = newChairId;
              removeChairFromPlacement(chairId);
              chairIdRenames[chairId] = newChairId;
              delete allChairSpots[chairId];
            }
            $(e).attr("id", newChairId);
            $(e).attr("onclick", "toggleChair('" + newChairId + "')");
          });
          for (let chairId of objectKeys(newChairSpots)) {
            allChairSpots[chairId] = newChairSpots[chairId];
          }
          for (let guestId of objectKeys(newPlacement)) {
            placement[guestId] = newPlacement[guestId];
          }
          applyChairIdRenames(chairIdRenames);
          updatePlacementInfo();
          for (let x = 0; x > -chairPairsToDelete; x--) {
            const topId = getChairId(tableId, "top", x);
            const bottomId = getChairId(tableId, "bottom", x);
            $("#" + topId).remove();
            $("#" + bottomId).remove();
            deleteChairSpot(topId);
            deleteChairSpot(bottomId);
          }
        } else {
          const nrOfChairs = $("#" + tableId + " .topChair").toArray().length;
          if (nrOfNewChairsX < nrOfChairs) {
            for (let x = nrOfChairs; x > nrOfNewChairsX; x--) {
              const topId = getChairId(tableId, "top", x);
              const bottomId = getChairId(tableId, "bottom", x);
              $("#" + topId).remove();
              $("#" + bottomId).remove();
              deleteChairSpot(topId);
              deleteChairSpot(bottomId);
            }
          }
        }
      }

      $("#" + tableId + " .chair").each((i, e) => {
        const chairId = $(e).attr("id") as ChairId | undefined;
        if (!chairId) return;
        const chairSpot = allChairSpots[chairId];
        if (!chairSpot) return;
        const { left, top } = getChairPosition(
          resizeSelector!.width(),
          resizeSelector!.height(),
          chairSpot.chairType,
          chairSpot.chairNr,
        );
        chairSpot.isHidden = false;
        $(e).css("top", top + "px");
        $(e).css("left", left + "px");
        $(e).show();
      });

      updateDisplayNumbers(tableId);
      updateAllTablesInfo();
      updateAllGuestList();
      updatePlacementInfo();
    } else if (!!draggableSelector) {
      tableId = draggableSelector.attr("id") as TableId | undefined;
      const { x, y } = mouseSpaceToRoomSpace(viewportMouseX, viewportMouseY);
      const roomMouseDiffX = x - roomMouseDownX;
      const roomMouseDiffY = y - roomMouseDownY;
      for (let selectedTable of selectedTables) {
        const { tableId, startCenterY, startCenterX, startRotation } = selectedTable;
        const moveX = snapTablesToGrid ? magnetizeValue(roomMouseDiffX, boxSize) : roomMouseDiffX;
        const moveY = snapTablesToGrid ? magnetizeValue(roomMouseDiffY, boxSize) : roomMouseDiffY;
        const newLeft = Math.min(Math.max(startCenterX + moveX, 0), BASE_ROOM_SIZE);
        const newTop = Math.min(Math.max(startCenterY + moveY, 0), BASE_ROOM_SIZE);
        const element = $("#" + tableId);
        element.css("left", newLeft + "px");
        element.css("top", newTop + "px");
        element.css("transform", rotateTransform(startRotation));
        if (snapTablesToGrid) snapToGrid(element);
      }
    }

    const selector = draggableSelector ?? resizeSelector ?? rotateSelector;
    if (selector) {
      for (let selectedTable of selectedTables) {
        const { tableId } = selectedTable;
        const element = $("#" + tableId);
        allTables[tableId] = {
          ...allTables[tableId],
          rotate: getRotation(tableId),
          width: element.width() ?? 0,
          height: element.height() ?? 0,
          centerX: parseInt(element.css("left")),
          centerY: parseInt(element.css("top")),
        };
      }
      for (let i = 0; i < selectedTables.length; i++) {
        const { tableId } = selectedTables[i];
        selectedTables[i].startCenterX = allTables[tableId].centerX;
        selectedTables[i].startCenterY = allTables[tableId].centerY;
        selectedTables[i].startRotation = allTables[tableId].rotate;
      }
      // Likes and dislikes are judged by seat distance, so moving, rotating
      // or resizing a table can flip a row even though nobody changed chair.
      // Runs after the write-back above so it sees the new geometry.
      updatePreferenceList();
    }

    if (guestBallSelector) {
      const guestBallId = guestBallSelector.attr("id");
      const ballGuestId = guestBallId?.split("guestBall_")[1] as GuestId | undefined;
      // Dropped on nothing: the ball glides back into its list row (a
      // chair-origin guest is unseated on the way) instead of vanishing.
      const before =
        ballGuestId && roomMode === "placementMode"
          ? captureGuestBallPositions([ballGuestId], {
              guestId: ballGuestId,
              element: guestBallSelector[0],
            })
          : undefined;
      guestBallSelector.remove();
      guestBallSelector = undefined;
      if (ballGuestId && guestBallSelectorType === "Chair") {
        delete placement[ballGuestId];
      }
      updateAllGuestList();
      updatePlacementInfo();
      if (before) {
        animateGuestBallsFrom(before, {
          durationMs: MANUAL_DROP_FLIGHT_MS,
          easing: MANUAL_DROP_FLIGHT_EASING,
        });
      }
    }

    if (rowSelector) {
      const guestId = (rowSelector.attr("id") ?? "") as GuestId;
      let added = false;

      if (startNewGroupGuestId) {
        const entryIndex = guestOrder.findIndex(
          (e) => !e.isGroup && e.guestId === startNewGroupGuestId,
        );
        if (entryIndex >= 0) {
          const groupId = mintId<GroupId>("group");
          const guestIds =
            startNewGroupPlace === "above"
              ? [guestId, startNewGroupGuestId]
              : [startNewGroupGuestId, guestId];
          allGroups[groupId] = {
            groupId,
            groupName: t("guests.newGroupName"),
            guestIds,
            mustSitTogether: false,
            likes: [],
            dislikes: [],
            allowedChairsByRoom: {},
            notAllowedChairsByRoom: {},
          };
          guestOrder[entryIndex] = { isGroup: true, groupId };
          added = true;
        }
      }

      let flatI = 0;
      for (let i = 0; i < guestOrder.length; i++) {
        const entry = guestOrder[i];
        if (entry.isGroup) {
          const group = allGroups[entry.groupId];
          if (flatI++ === newListIndex && !added) {
            guestOrder.splice(i, 0, { isGroup: false, guestId });
            added = true;
          }
          if (!added) {
            for (let j = 0; j < group.guestIds.length; j++) {
              if (flatI++ === newListIndex) {
                group.guestIds.splice(j, 0, guestId);
                added = true;
                break;
              }
            }
          }
          if (flatI++ === newListIndex && !added) {
            group.guestIds.push(guestId);
            added = true;
          }
        } else {
          if (flatI++ === newListIndex && !added) {
            guestOrder.splice(i, 0, { isGroup: false, guestId });
            added = true;
          }
        }
        if (added) break;
      }
      if (!added) {
        guestOrder.push({ isGroup: false, guestId });
      }

      for (let i = guestOrder.length - 1; i >= 0; i--) {
        const entry = guestOrder[i];
        if (entry.isGroup && allGroups[entry.groupId].guestIds.length === 0) {
          delete allGroups[entry.groupId];
          guestOrder.splice(i, 1);
        }
      }
      closePreferencesIfSubjectGone();

      rowSelector.remove();
      guestListVirtualizationSuspended = false;
      updateAllGuestList();
    }

    draggableSelector = undefined;
    resizeSelector = undefined;
    rotateSelector = undefined;
    guestBallSelector = undefined;
    rowSelector = undefined;

    $("body").removeClass("isGrabbing").removeClass("unselectableText");

    moveRoom = false;
    $("#canvas").css("cursor", "");
    hideCustomCursor();
    clearTimeout(startNewGroupTimer);
  });

  let guestListScrollFrame: number | undefined = undefined;
  document.querySelector("#stepPanel .scrollContainer")?.addEventListener("scroll", () => {
    if (guestListVirtualizationSuspended || guestListScrollFrame !== undefined) return;
    guestListScrollFrame = requestAnimationFrame(() => {
      guestListScrollFrame = undefined;
      const { layout } = getGuestOrderLayout();
      const range = getGuestListRenderRange(layout);
      if (
        lastGuestListRenderRange &&
        range.start === lastGuestListRenderRange.start &&
        range.end === lastGuestListRenderRange.end
      ) {
        return;
      }
      updateAllGuestList();
    });
  });

  $("#room").on("mouseup", ".chairIsChair", function () {
    if (guestBallSelector !== undefined && roomMode === "placementMode") {
      const thisChairId = ($(this).attr("id") ?? "") as ChairId;

      const guestBallId = guestBallSelector.attr("id") ?? "";
      const ballGuestId = guestBallId.split("guestBall_")[1] as GuestId;

      let occupiedByGuestId: GuestId | undefined = undefined;
      for (let guestId of objectKeys(placement)) {
        const chairId = placement[guestId];
        if (thisChairId === chairId) {
          occupiedByGuestId = guestId;
          break;
        }
      }

      // Measured before anything moves: the dropped ball then snaps from the
      // drop point into the chair, and a displaced occupant flies to the
      // dragged guest's old chair or back into its list row.
      const before = captureGuestBallPositions(
        occupiedByGuestId ? [occupiedByGuestId, ballGuestId] : [ballGuestId],
        { guestId: ballGuestId, element: guestBallSelector[0] },
      );

      if (occupiedByGuestId) {
        if (placement[ballGuestId]) {
          // Switch places
          $(`#guestChairBall_${occupiedByGuestId}`).remove();
          addGuestToChair(occupiedByGuestId, placement[ballGuestId]);
        } else {
          // Remove current guest on chair
          $(`#guestChairBall_${occupiedByGuestId}`).remove();
          delete placement[occupiedByGuestId];
        }
      }

      $(`#guestChairBall_${ballGuestId}`).remove();
      addGuestToChair(ballGuestId, thisChairId);
      selectOneGuest(ballGuestId);

      updateAllGuestList();
      updatePlacementInfo();
      guestBallSelector.remove();
      guestBallSelector = undefined;

      animateGuestBallsFrom(before, {
        durationMs: MANUAL_DROP_FLIGHT_MS,
        easing: MANUAL_DROP_FLIGHT_EASING,
      });
    }
  });

  $("#body").on("mouseup", ".preferenceBox", function () {
    const highlightedGuestId = getHighlightedGuestId();
    if (guestBallSelector !== undefined && highlightedGuestId) {
      const thisBoxId = $(this).attr("id") ?? "";
      const type = thisBoxId.split("guestBox")[1] as "Likes" | "Dislikes";

      const guestBallId = guestBallSelector.attr("id") ?? "";
      const ballGuestId = guestBallId.split("guestBall_")[1] as GuestId;

      if (ballGuestId !== highlightedGuestId) {
        const success = addGuestToPreference(ballGuestId, highlightedGuestId, type);
        if (success) addGuestToPreferenceVisually(ballGuestId, highlightedGuestId, thisBoxId, type);
      }
    }
  });

  const backSpaceKey = 8;
  const deleteKey = 46;
  const cKey = 67;
  const vKey = 86;
  let nrOfPaste = 0;

  $(document).on("keydown", function (e) {
    if (isModalOverlayOpen()) return;
    // Ctrl on Windows/Linux, Cmd on Mac — read off the event, see the
    // moveHandle handler for why no flag is tracked.
    const commandHeld = e.ctrlKey || e.metaKey;

    if (commandHeld && e.which === cKey) {
      if (selectedTables.length > 0) {
        clipboard = [];
        for (let selectedTable of selectedTables) {
          const { tableId } = selectedTable;
          const table = { ...allTables[tableId] };
          const chairs: ChairSpot[] = [];
          for (let chairId of objectKeys(allChairSpots)) {
            const chair = allChairSpots[chairId];
            if (chair.tableId === tableId) {
              chairs.push({ ...chair });
            }
          }
          clipboard.push({ table, chairs });
          nrOfPaste = 0;
        }
      } else {
        clipboard = undefined;
      }
    }
    if (commandHeld && e.which === vKey) {
      if (clipboard) {
        recordHistory();
        nrOfPaste++;
        unselectAllTables();
        const newTableIds: TableId[] = [];
        for (let clipboardTable of clipboard) {
          const { table, chairs } = clipboardTable;
          let newTableId: TableId | undefined = undefined;
          if (table.type === "square") {
            newTableId = addSquareTable({
              ...table,
              centerY: table.centerY + boxSize * nrOfPaste,
              centerX: table.centerX + boxSize * nrOfPaste,
            });
          }
          if (table.type === "round") {
            newTableId = addRoundTable({
              ...table,
              centerY: table.centerY + boxSize * nrOfPaste,
              centerX: table.centerX + boxSize * nrOfPaste,
            });
          }
          if (table.type === "bench") {
            newTableId = addBenchTable({
              ...table,
              centerY: table.centerY + boxSize * nrOfPaste,
              centerX: table.centerX + boxSize * nrOfPaste,
            });
          }
          for (let chair of chairs) {
            if (newTableId) addChairSpot(newTableId, chair.chairType, chair.chairNr, chair.isChair);
          }
          if (newTableId) newTableIds.push(newTableId);
        }
        selectTables(newTableIds);
        updateAllTablesInfo();
        updatePlacementInfo();
      }
    }
    if (e.which === deleteKey || e.which === backSpaceKey) {
      const textAreaFocused = $("#addMoreGuests").is(":focus");
      const addGuestInputFocused =
        $("#addGuestInput").is(":focus") || $("#guestSearchInput").is(":focus");
      const tableInputFocused = $(".tableInput").is(":focus");
      const guestInputFocused = $("#highlightedGuestInput").is(":focus");
      const projectNameFocused = $("#projectNameInput").is(":focus");

      if (
        textAreaFocused ||
        addGuestInputFocused ||
        tableInputFocused ||
        guestInputFocused ||
        projectNameFocused
      )
        return;

      // removeTable/removeGuest each record on their own (they're also
      // button handlers); batched so a multi-select delete is one undo step.
      batchHistory(() => {
        for (let selectedTable of [...selectedTables]) {
          const { tableId } = selectedTable;
          removeTable(tableId);
        }

        // Removing a table unselects its guest,
        // meaning that if both tables and guests
        // are selected only the tables will be deleted.

        for (let selectedGuest of [...selectedGuests]) {
          const { guestId } = selectedGuest;
          removeGuest(guestId);
        }
      });
    }
  });

  // Delegated on document (focus doesn't bubble, focusin does): the table list
  // rebuilds its inputs, so handlers bound directly to inputs would miss them.
  $(document).on("focusin", "input, textarea", function () {
    clipboard = undefined;
  });
});
