const getAllowedChairs = (entity: Guest | Group): ChairId[] =>
  entity.allowedChairsByRoom[currentRoomId] ?? [];
const getNotAllowedChairs = (entity: Guest | Group): ChairId[] =>
  entity.notAllowedChairsByRoom[currentRoomId] ?? [];

// The fulfilled-preferences list sits above the guest list, so letting it
// grow while guest balls are flying would shift every row under them.
// autoPlace.ts suspends it for the apply and runs it once the flight lands.
let preferenceListUpdatesSuspended = false;

const updatePreferenceList = () => {
  if (preferenceListUpdatesSuspended) return;
  $("#fulfilledPreferences").html("");

  for (let i = 0; i < guestOrder.length; i++) {
    const entry = guestOrder[i];
    if (entry.isGroup) {
      appendPreferencesForGroup(entry.groupId);
      const group = allGroups[entry.groupId];
      for (let guestId of group.guestIds) {
        appendPreferencesForGuest(guestId);
      }
    } else {
      appendPreferencesForGuest(entry.guestId);
    }
  }
  const html = $("#fulfilledPreferences").html();
  if (html === "") {
    $(".fulfilledPreferences").hide();
  } else {
    $(".fulfilledPreferences").show();
  }
};

const appendPreferencesForGroup = (groupId: GroupId) => {
  let group = allGroups[groupId];
  if (!group) return;

  let groupIsPlaced = false;
  for (let g of group.guestIds) {
    const guestChairId = placement[g];
    if (guestChairId) groupIsPlaced = true;
  }
  if (!groupIsPlaced) return;

  let html = "";

  // Same table, as the worker scores it (placementWorker.ts): judged over
  // the members who are seated so far.
  if (group.mustSitTogether) {
    const seatedChairs: ChairId[] = [];
    const tables = new Set<TableId>();
    for (let g of group.guestIds) {
      const guestChairId = placement[g];
      const chair = guestChairId ? allChairSpots[guestChairId] : undefined;
      if (!chair || !chair.isChair) continue;
      seatedChairs.push(chair.chairId);
      tables.add(chair.tableId);
    }
    const preferenceFulfilled = tables.size === 1;
    html += `<p
    style="${preferenceFulfilled ? "color: var(--green)" : "color: var(--red)"}"
    onmouseover="highlightPreferenceChairs([${seatedChairs.map((c) => "'" + c + "'").join(",")}])"
    onmouseout="stopHighlightPreferenceChairs()"
    >
    ${t("fulfilled.groupSitsTogether", { group: group.groupName })}
    </p>`;
  }

  const groupAllowedChairs = getAllowedChairs(group);
  const groupNotAllowedChairs = getNotAllowedChairs(group);

  if (groupAllowedChairs.length > 0) {
    let preferenceFulfilled = true;
    const highlightChairs: ChairId[] = [];
    for (let g of group.guestIds) {
      const guestChairId = placement[g];
      if (!guestChairId) continue;
      highlightChairs.push(guestChairId);
      if (!groupAllowedChairs.includes(guestChairId)) {
        preferenceFulfilled = false;
      }
    }
    html += `<p
    style="${preferenceFulfilled ? "color: var(--green)" : "color: var(--red)"}"
    onmouseover="highlightPreferenceChairs([${highlightChairs.map((g) => "'" + g + "'").join(",")}])"
    onmouseout="stopHighlightPreferenceChairs()"
    >
    ${t("fulfilled.groupOnlyAllowed", { group: group.groupName })}`;

    for (let i = 0; i < groupAllowedChairs.length; i++) {
      const chairId = groupAllowedChairs[i];
      const chair = allChairSpots[chairId];
      if (chair && chair.isChair) {
        const table = allTables[chair.tableId];
        html +=
          `${table.label} ${chairNumbers[chairId]}` +
          (i < groupAllowedChairs.length - 1 ? ", " : "");
      }
    }
    html += "</p>";
  } else if (groupNotAllowedChairs.length > 0) {
    let preferenceFulfilled = true;
    const highlightChairs: ChairId[] = [];
    for (let g of group.guestIds) {
      const guestChairId = placement[g];
      if (!guestChairId) continue;
      highlightChairs.push(guestChairId);
      if (groupNotAllowedChairs.includes(guestChairId)) {
        preferenceFulfilled = false;
      }
    }
    html += `<p
    style="${preferenceFulfilled ? "color: var(--green)" : "color: var(--red)"}"
    onmouseover="highlightPreferenceChairs([${highlightChairs.map((g) => "'" + g + "'").join(",")}])"
    onmouseout="stopHighlightPreferenceChairs()"
    >
    ${t("fulfilled.groupNotAllowed", { group: group.groupName })}`;

    for (let i = 0; i < groupNotAllowedChairs.length; i++) {
      const chairId = groupNotAllowedChairs[i];
      const chair = allChairSpots[chairId];
      if (chair && chair.isChair) {
        const table = allTables[chair.tableId];
        html +=
          `${table.label} ${chairNumbers[chairId]}` +
          (i < groupNotAllowedChairs.length - 1 ? ", " : "");
      }
    }
    html += "</p>";
  }

  $("#fulfilledPreferences").append(html);
};

// Distance between two seated guests in chair units — the same measure the
// worker scores with (see WorkerInput in autoPlace.ts), so the list below
// turns green exactly when the score says the wish is met.
const seatedDistanceInChairUnits = (a: ChairSpot, b: ChairSpot): number => {
  const pa = getChairRoomPosition(a, 0);
  const pb = getChairRoomPosition(b, 0);
  return Math.hypot(pa.x - pb.x, pa.y - pb.y) / arcLenghtBetween2Chairs;
};

const appendPreferencesForGuest = (guestId: GuestId) => {
  const guest = allGuests[guestId];
  if (!guest) return;

  const guestChairId = placement[guestId];
  if (!guestChairId) return;
  const guestChair = allChairSpots[guestChairId];
  if (!guestChair || !guestChair.isChair) return;

  let html = "";

  for (let other of guest.likes) {
    let preferenceFulfilled = false;

    const otherGuest = allGuests[other];
    if (!otherGuest) continue;

    const otherChairId = placement[other];
    if (!otherChairId) continue;
    const otherChair = allChairSpots[otherChairId];
    if (!otherChair || !otherChair.isChair) continue;

    // Same table and within reach — not merely somewhere along a long table.
    if (
      guestChair.tableId === otherChair.tableId &&
      reach(seatedDistanceInChairUnits(guestChair, otherChair), LIKE_RADIUS) > 0
    ) {
      preferenceFulfilled = true;
    }

    html += `<p
    style="${preferenceFulfilled ? "color: var(--green)" : "color: var(--red)"}"
    onmouseover="highlightPreferenceChairs(['${guestChairId}', '${otherChairId}'])"
    onmouseout="stopHighlightPreferenceChairs()"
    >
    ${t("fulfilled.like", { guest: guest.name, other: otherGuest.name })}
    </p>`;
  }

  for (let other of guest.dislikes) {
    let preferenceFulfilled = false;

    const otherGuest = allGuests[other];
    if (!otherGuest) continue;

    const otherChairId = placement[other];
    if (!otherChairId) continue;
    const otherChair = allChairSpots[otherChairId];
    if (!otherChair || !otherChair.isChair) continue;

    // Out of reach, whatever the table — the next table over can be too close.
    if (reach(seatedDistanceInChairUnits(guestChair, otherChair), DISLIKE_RADIUS) === 0) {
      preferenceFulfilled = true;
    }

    html += `<p
    style="${preferenceFulfilled ? "color: var(--green)" : "color: var(--red)"}"
    onmouseover="highlightPreferenceChairs(['${guestChairId}', '${otherChairId}'])"
    onmouseout="stopHighlightPreferenceChairs()"
    >
    ${t("fulfilled.dislike", { guest: guest.name, other: otherGuest.name })}
    </p>`;
  }

  const guestAllowedChairs = getAllowedChairs(guest);
  const guestNotAllowedChairs = getNotAllowedChairs(guest);

  if (guestAllowedChairs.length > 0) {
    let preferenceFulfilled = false;
    if (guestAllowedChairs.includes(guestChairId)) {
      preferenceFulfilled = true;
    }
    html += `<p
    style="${preferenceFulfilled ? "color: var(--green)" : "color: var(--red)"}"
    onmouseover="highlightPreferenceChairs(['${guestChairId}'])"
    onmouseout="stopHighlightPreferenceChairs()"
    >
    ${t("fulfilled.onlyAllowed", { guest: guest.name })}`;

    for (let i = 0; i < guestAllowedChairs.length; i++) {
      const chairId = guestAllowedChairs[i];
      const chair = allChairSpots[chairId];
      if (chair && chair.isChair) {
        const table = allTables[chair.tableId];
        html +=
          `${table.label} ${chairNumbers[chairId]}` +
          (i < guestAllowedChairs.length - 1 ? ", " : "");
      }
    }
    html += "</p>";
  } else if (guestNotAllowedChairs.length > 0) {
    let preferenceFulfilled = false;
    if (!guestNotAllowedChairs.includes(guestChairId)) {
      preferenceFulfilled = true;
    }
    html += `<p
    style="${preferenceFulfilled ? "color: var(--green)" : "color: var(--red)"}"
    onmouseover="highlightPreferenceChairs(['${guestChairId}'])"
    onmouseout="stopHighlightPreferenceChairs()"
    >
    ${t("fulfilled.notAllowed", { guest: guest.name })}`;

    for (let i = 0; i < guestNotAllowedChairs.length; i++) {
      const chairId = guestNotAllowedChairs[i];
      const chair = allChairSpots[chairId];
      if (chair && chair.isChair) {
        const table = allTables[chair.tableId];
        html +=
          `${table.label} ${chairNumbers[chairId]}` +
          (i < guestNotAllowedChairs.length - 1 ? ", " : "");
      }
    }
    html += "</p>";
  }

  $("#fulfilledPreferences").append(html);
};

const highlightPreferenceChairs = (chairIds: ChairId[]) => {
  stopHighlightPreferenceChairs();
  if (roomMode !== "placementMode") return;

  for (let guestId of objectKeys(placement)) {
    const id = placement[guestId];
    if (chairIds.includes(id)) {
      $("#" + id).addClass("preferenceHighlightedChair");
    } else {
      $("#" + id).addClass("preferenceNotHighlightedChair");
    }
  }
};
const stopHighlightPreferenceChairs = () => {
  $(".chair").removeClass("preferenceHighlightedChair");
  $(".chair").removeClass("preferenceNotHighlightedChair");
};
