type WorkerGuestInput = {
  guestId: GuestId;
  groupId?: GroupId;
  mustSitTogether?: boolean;
  likes: GuestId[];
  dislikes: GuestId[];
  allowedChairs: ChairId[];
  notAllowedChairs: ChairId[];
  pinnedChairId?: ChairId;
};
type WorkerInput = {
  // x/y are room-space positions of a SEATED guest — the chair pulled in to
  // the table edge, not where the chair is drawn — normalized so 1 unit ≈
  // the distance between two adjacent chairs (see arcLenghtBetween2Chairs in
  // types.ts). Across a standard-depth table is then 1.5, closer than two
  // chairs down the row, which is how the worker's distance-based scoring
  // treats facing guests as near without any special case.
  chairs: { chairId: ChairId; tableId: TableId; x: number; y: number }[];
  guests: WorkerGuestInput[];
};
type WorkerReadyMessage = { type: "ready" };
type WorkerProgressMessage = {
  type: "progress";
  restart: number;
  bestScore: number;
};
type WorkerDoneMessage = {
  type: "done";
  placement: { [guestId: GuestId]: ChairId };
  score: number;
};

const findGroupForGuest = (guestId: GuestId): Group | undefined => {
  for (let groupId of objectKeys(allGroups)) {
    if (allGroups[groupId].guestIds.includes(guestId)) return allGroups[groupId];
  }
  return undefined;
};

const getEffectiveChairConstraints = (guestId: GuestId, group: Group | undefined) => {
  const guest = allGuests[guestId];
  const guestAllowedChairs = getAllowedChairs(guest);
  const guestNotAllowedChairs = getNotAllowedChairs(guest);
  const groupAllowedChairs = group ? getAllowedChairs(group) : [];
  const groupNotAllowedChairs = group ? getNotAllowedChairs(group) : [];

  const notAllowed = new Set([...guestNotAllowedChairs, ...groupNotAllowedChairs]);

  let allowed: ChairId[] = [];
  if (guestAllowedChairs.length > 0 && groupAllowedChairs.length > 0) {
    const groupAllowedSet = new Set(groupAllowedChairs);
    allowed = guestAllowedChairs.filter((c) => groupAllowedSet.has(c));
  } else if (guestAllowedChairs.length > 0) {
    allowed = guestAllowedChairs;
  } else if (groupAllowedChairs.length > 0) {
    allowed = groupAllowedChairs;
  }

  return { allowedChairs: allowed, notAllowedChairs: [...notAllowed] };
};

const buildWorkerInput = (onlyRemaining: boolean): WorkerInput => {
  const chairs = Object.values(allChairSpots)
    .filter((c) => c.isChair && !c.isHidden)
    .map((c) => {
      // Gap 0: the seated position, see WorkerInput.chairs.
      const { x, y } = getChairRoomPosition(c, 0);
      return {
        chairId: c.chairId,
        tableId: c.tableId,
        x: x / arcLenghtBetween2Chairs,
        y: y / arcLenghtBetween2Chairs,
      };
    });

  const guests: WorkerGuestInput[] = [];
  for (let guestId of objectKeys(allGuests)) {
    const guest = allGuests[guestId];
    const group = findGroupForGuest(guestId);
    const { allowedChairs, notAllowedChairs } = getEffectiveChairConstraints(guestId, group);

    guests.push({
      guestId,
      groupId: group?.groupId,
      mustSitTogether: group?.mustSitTogether,
      likes: guest.likes,
      dislikes: guest.dislikes,
      allowedChairs,
      notAllowedChairs,
      pinnedChairId: onlyRemaining ? placement[guestId] : undefined,
    });
  }

  return { chairs, guests };
};

const applyAutoPlacementResult = (result: WorkerDoneMessage) => {
  recordHistory();
  setRoomMode("placementMode");
  $(".chairContent .guestBall").remove();
  for (let guestId of objectKeys(placement)) delete placement[guestId];

  for (let guestId of objectKeys(result.placement)) {
    if (!allGuests[guestId]) continue;
    const chairId = result.placement[guestId];
    const chair = allChairSpots[chairId];
    if (!chair) continue;

    renderGuestBallDom(guestId, chairId);
    placement[guestId] = chairId;
  }

  updateChairGuestBallNames();
  updatePlacementInfo();
  updateAllGuestList();
};

let placementWorker: Worker | undefined = undefined;
// Identifies the run whose result is still wanted. Bumped by every new run
// and by cancelPendingAutoPlacement, so a worker reply or the cover timer
// from an older run is simply dropped.
let autoPlaceRunId = 0;
// The loading cover shows for at least this long, even when the worker is
// quicker — a blink of a spinner reads as a glitch, not as "thinking".
const MIN_ROOM_LOADING_COVER_MS = 500;

const finishAutoPlacementUi = () => {
  document.body.classList.remove("autoPlacing");
  hideRoomLoadingCover();
};

// Drops a run that is still computing: the arrangement under it is being
// changed (undo/redo through liveUpdate.ts, a restore or an opened file
// through replaceAllData), so its result would land on the wrong state.
const cancelPendingAutoPlacement = () => {
  autoPlaceRunId++;
  if (placementWorker) {
    placementWorker.terminate();
    placementWorker = undefined;
  }
  finishAutoPlacementUi();
};

// Shows the result: the DOM is updated as before, but with the balls measured
// first so each one flies from where it was to where it ends up.
const presentAutoPlacementResult = async (
  result: WorkerDoneMessage,
  before: Map<GuestId, GuestBallSnapshot>,
) => {
  hideRoomLoadingCover();
  preferenceListUpdatesSuspended = true;
  try {
    applyAutoPlacementResult(result);
    await animateGuestBallsFrom(before, {
      durationMs: AUTO_PLACE_FLIGHT_MS,
      easing: AUTO_PLACE_FLIGHT_EASING,
    });
  } finally {
    preferenceListUpdatesSuspended = false;
    updatePreferenceList();
    document.body.classList.remove("autoPlacing");
  }
};

const runAutoPlacement = (onlyRemaining: boolean) => {
  // Each button is disabled on its own terms (see updatePlacementInfo), so
  // check the one that was pressed — not the pair.
  const button = onlyRemaining ? "#createPlacementButtonRest" : "#createPlacementButton";
  if ($(button).hasClass("button-disabled")) return;
  if (document.body.classList.contains("autoPlacing")) return;
  if (placementWorker) placementWorker.terminate();

  const input = buildWorkerInput(onlyRemaining);
  if (input.guests.length === 0) return;

  unselectAllGuests();
  unselectAllTables();
  updatePlacementInfo();
  // Mode before the list render: list balls take their table colour at
  // render time, and the flight's start colours are measured from it.
  setRoomMode("placementMode");
  updateAllGuestList();

  const runId = ++autoPlaceRunId;
  const roomId = currentRoomId;
  const startedAt = performance.now();
  document.body.classList.add("autoPlacing");
  showRoomLoadingCover();
  const before = captureGuestBallPositions(objectKeys(allGuests));

  const worker = new Worker("/app/worker/placementWorkerBootstrap.js");
  placementWorker = worker;
  worker.onerror = (error) => {
    console.error("Auto placement failed:", error);
    worker.terminate();
    if (placementWorker === worker) placementWorker = undefined;
    if (runId === autoPlaceRunId) finishAutoPlacementUi();
  };
  worker.onmessage = (
    e: MessageEvent<WorkerReadyMessage | WorkerProgressMessage | WorkerDoneMessage>,
  ) => {
    if (e.data.type === "ready") {
      worker.postMessage(input);
      return;
    }
    if (e.data.type !== "done") return;
    const result = e.data;
    worker.terminate();
    if (placementWorker === worker) placementWorker = undefined;

    const remainingMs = Math.max(0, MIN_ROOM_LOADING_COVER_MS - (performance.now() - startedAt));
    window.setTimeout(() => {
      // Cancelled meanwhile: that path already restored the UI.
      if (runId !== autoPlaceRunId) return;
      if (roomId !== currentRoomId) {
        finishAutoPlacementUi();
        return;
      }
      presentAutoPlacementResult(result, before);
    }, remainingMs);
  };
};

$(() => {
  $("#createPlacementButton").on("click", () => runAutoPlacement(false));
  $("#createPlacementButtonRest").on("click", () => runAutoPlacement(true));
});
