// Square chairs:
//               (top, 1)(top, 2)(top, 3)
//       (left, 1)                        (right, 1)
//       (left, 2)                        (right, 2)
//       (left, 3)                        (right, 3)
//              (bottom, 1)(b.., 2)(b.., 3)
//
// Round chairs:
//       (1)
// (6)         (2)
//
// (5)         (3)
//       (4)

const getChairId = (tableId: TableId, chairType: ChairType, chairNr: number): ChairId =>
  (tableId + "_chair_" + chairType + "_nr_" + chairNr) as ChairId;

// The 500 points sampled around a round table's ellipse only depend on the
// table's own width/height, not on which chair we're placing — callers that
// position more than one chair on the same table in a loop (e.g. the resize
// handlers in interactions.ts) should call this once and pass the result to
// every getChairPosition call for that table, instead of paying for a fresh
// 500-point sample per chair.
const getRoundTableSamplePoints = (
  tableWidth: number | undefined,
  tableHeight: number | undefined,
) => {
  const samplePoints: { x: number; y: number }[] = [];
  const a = (tableWidth ?? 0) / 2;
  const b = (tableHeight ?? 0) / 2;
  const M = 500;
  for (let i = 0; i < M; i++) {
    const t = (2 * Math.PI * i) / M - Math.PI / 2;
    samplePoints.push({ x: a * Math.cos(t), y: b * Math.sin(t) });
  }
  return samplePoints;
};

const getChairPosition = (
  tableWidth: number | undefined,
  tableHeight: number | undefined,
  chairType: ChairType,
  chairNr: number,
  roundSamplePoints?: { x: number; y: number }[],
  gapChairTable: number = GAP_CHAIR_TABLE,
) => {
  const nrPos = 2 * boxSize * chairNr - boxSize / 2;
  if (chairType === "top") return { left: nrPos, top: -gapChairTable };
  if (chairType === "left") return { left: -gapChairTable, top: nrPos };
  if (chairType === "bottom") return { left: nrPos, top: (tableHeight ?? 0) + gapChairTable };
  if (chairType === "right") return { left: (tableWidth ?? 0) + gapChairTable, top: nrPos };
  if (chairType === "round") {
    const samplePoints = roundSamplePoints ?? getRoundTableSamplePoints(tableWidth, tableHeight);
    const a = (tableWidth ?? 0) / 2;
    const b = (tableHeight ?? 0) / 2;

    const distance = (p1: { x: number; y: number }, p2: { x: number; y: number }) => {
      return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
    };

    const arcLenghtGoal = arcLenghtBetween2Chairs * (chairNr - 1);
    let accArcLength = 0;
    let bestPointIndex = 0;
    let prevPoint = samplePoints[0];
    for (let i = 1; i < samplePoints.length; i++) {
      const lastAccArcLength = accArcLength;
      accArcLength += distance(prevPoint, samplePoints[i]);
      if (accArcLength > arcLenghtGoal) {
        if (Math.abs(lastAccArcLength - arcLenghtGoal) < Math.abs(accArcLength - arcLenghtGoal))
          bestPointIndex = i - 1;
        else bestPointIndex = i;
        break;
      }
      prevPoint = samplePoints[i];
    }

    const bestPoint = samplePoints[bestPointIndex];
    // Outward normal of the ellipse x²/a²+y²/b²=1 at (x,y) points along
    // (x/a², y/b²) — same gradient trick as the resize cursor in cursor.ts
    // and the chair-name rotation in export.ts. Stepping GAP_CHAIR_TABLE
    // along that normalized direction puts the chair a true perpendicular
    // distance from the table edge; previously this just scaled both radii
    // by GAP_CHAIR_TABLE, which only matches the true normal offset at the
    // ellipse's 4 axis vertices — everywhere else on a non-circular table it
    // drifted off-normal (bunching chairs closer/farther than intended).
    const nx = bestPoint.x / (a * a);
    const ny = bestPoint.y / (b * b);
    const nLen = Math.sqrt(nx * nx + ny * ny) || 1;

    return {
      left: a + bestPoint.x + (nx / nLen) * gapChairTable,
      top: b + bestPoint.y + (ny / nLen) * gapChairTable,
    };
  }
  return { left: 0, top: 0 };
};

// Absolute room-space center of a chair: local offset from getChairPosition,
// rotated and translated by the owning table's own placement (mirrors the
// translate(-50%,-50%) rotate() transform tables render with, see rotateXY
// usages in interactions.ts). table.centerX/table.centerY are already the
// table's visual center in room space, so the rotated local offset is added
// directly with no extra half-width/half-height term.
const getChairRoomPosition = (
  chairSpot: ChairSpot,
  gapChairTable: number = GAP_CHAIR_TABLE,
): { x: number; y: number } => {
  const table = allTables[chairSpot.tableId];
  const { left, top } = getChairPosition(
    table.width,
    table.height,
    chairSpot.chairType,
    chairSpot.chairNr,
    undefined,
    gapChairTable,
  );
  const rotated = rotateXY(
    left - table.width / 2,
    top - table.height / 2,
    table.rotate * DEG_TO_RAD,
  );
  return {
    x: table.centerX + rotated.x,
    y: table.centerY + rotated.y,
  };
};

// Builds the DOM node for an already-created ChairSpot (allChairSpots[chairId] must
// already be set, and its owning table must already be rendered). Used both by
// addChairSpot right after minting a new chair, and by switchRoom to rehydrate a
// room's existing chairs without minting new ones.
const renderChairDom = (chairSpot: ChairSpot) => {
  const { chairId, tableId, chairType, chairNr, isChair } = chairSpot;
  const tableWidth = $("#" + tableId).width();
  const tableHeight = $("#" + tableId).height();
  const { left, top } = getChairPosition(tableWidth, tableHeight, chairType, chairNr);
  const chairClass = chairType + "Chair";
  const colorToken = allTables[tableId].colorToken;
  const color = getColor(colorToken);
  const colorDark = getDarkColor(colorToken);
  const backgroundColor = getLightColor(colorToken);
  const rotation = getRotation(tableId);
  const style = "top: " + top + "px; left: " + left + "px;";
  const isTableSelected = isSelectedTable(tableId);
  const contentStyle =
    roomMode === "preferenceMode"
      ? "border-color: var(--greySemi); "
      : "border-color: " +
        (isTableSelected ? colorDark : color) +
        "; background: " +
        backgroundColor;

  const chairOrChairSpot = isChair ? "chairIsChair" : "chairIsSpot";

  const transform = rotateTransform(-rotation);
  const adjustRotation = "transform: " + transform;

  $("#" + tableId).append(
    `<div
      id="${chairId}"
      onclick="toggleChair('${chairId}')"
      class="chair ${chairOrChairSpot} ${chairClass} unselectableText"
      style="${style}">
      <div class="chairContent" style="${contentStyle}">
        <p class="chairLabel adjustRotation" style="${adjustRotation}"></p>
      </div>
    </div>`,
  );
};

const addChairSpot = (
  tableId: TableId,
  chairType: ChairType,
  chairNr: number,
  isChairFromProps?: boolean,
) => {
  const chairId = getChairId(tableId, chairType, chairNr);

  const prevChairId = getChairId(tableId, chairType, chairNr - 1);
  const nextChairId = getChairId(tableId, chairType, chairNr + 1);
  const isChair =
    isChairFromProps ??
    allChairSpots[prevChairId]?.isChair ??
    allChairSpots[nextChairId]?.isChair ??
    true;

  const chairSpot: ChairSpot = { chairId, tableId, isChair, chairType, chairNr };
  allChairSpots[chairId] = chairSpot;
  renderChairDom(chairSpot);

  updateDisplayNumbers(tableId);
};

const toggleChair = (chairId: ChairId) => {
  recordHistory();
  if (roomMode === "preferenceMode") {
    toggleChairPreference(chairId);
    return;
  }
  if (roomMode !== "buildMode") return;
  const chairSpot = allChairSpots[chairId];
  const { isChair } = chairSpot;
  const oldClass = isChair ? "chairIsChair" : "chairIsSpot";
  const newClass = !isChair ? "chairIsChair" : "chairIsSpot";
  $("#" + chairId)
    .removeClass(oldClass)
    .addClass(newClass);
  allChairSpots[chairId] = {
    ...chairSpot,
    isChair: !isChair,
  };

  if (isChair) {
    const guestId = getGuestOnChair(chairId);
    if (guestId) $(`#guestChairBall_${guestId}`).remove();
    removeChairFromPlacement(chairId);
  }

  updateDisplayNumbers(chairSpot.tableId);
  updateAllTablesInfo();
  updatePlacementInfo();
  selectOneTable(chairSpot.tableId);
};

const hideChair = (chairId: ChairId) => {
  if (allChairSpots[chairId].isHidden) return false;

  allChairSpots[chairId].isHidden = true;
  $("#" + chairId).hide();
  return true;
};
const showChair = (chairId: ChairId) => {
  if (!allChairSpots[chairId].isHidden) return false;

  allChairSpots[chairId].isHidden = false;
  $("#" + chairId).show();
  return true;
};

// The number shown on every chair that is one (gaps and hidden chairs have
// no entry). getExportChairNumbers counts entries per table for the global
// numbering, so an entry must go the moment its chair stops being one.
let chairNumbers: { [chairId: ChairId]: number } = {};

// The order chairs are numbered in around a table: round tables by chairNr
// (a ring), square ones clockwise from the top-left — top and right
// ascending, bottom and left descending.
const sortChairSpotsForNumbering = (chairs: ChairSpot[]): ChairSpot[] => {
  if (chairs.length === 0) return chairs;
  if (chairs[0].chairType === "round") return [...chairs].sort((a, b) => a.chairNr - b.chairNr);
  const side = (chairType: ChairType, ascending: boolean) =>
    chairs
      .filter((c) => c.chairType === chairType)
      .sort((a, b) => (ascending ? a.chairNr - b.chairNr : b.chairNr - a.chairNr));
  return [
    ...side("top", true),
    ...side("right", true),
    ...side("bottom", false),
    ...side("left", false),
  ];
};

const chairSpotsOfTable = (tableId: TableId): ChairSpot[] =>
  objectKeys(allChairSpots)
    .filter((chairId) => allChairSpots[chairId].tableId === tableId)
    .map((chairId) => allChairSpots[chairId]);

// Pure: the display number of every chair of the table that is one — not a
// gap, not hidden — 1..n in numbering order. The room on screen gets its
// labels from this (updateDisplayNumbers); the guests' page (guestPage.ts)
// numbers a published room with it, where there is no room DOM at all.
const computeTableChairNumbers = (tableId: TableId): { [chairId: ChairId]: number } => {
  const numbers: { [chairId: ChairId]: number } = {};
  let displayNr = 1;
  for (const chairSpot of sortChairSpotsForNumbering(chairSpotsOfTable(tableId))) {
    if (chairSpot.isChair && !chairSpot.isHidden) numbers[chairSpot.chairId] = displayNr++;
  }
  return numbers;
};

// Draws one table's chairs again from its data — after a chair came, went
// or changed, or the table changed size — with their numbers, the balls of
// the guests seated there, and the mode's chair styling (as renderRoomDom
// does for a whole room).
// Forgets the numbers of chairs that are gone from the data (a table or a
// chair removed under the DOM by undo or a version from elsewhere); the
// build path's deleteChairSpot does the same per chair.
const pruneChairNumbers = () => {
  for (const chairId of objectKeys(chairNumbers)) {
    if (!allChairSpots[chairId]) delete chairNumbers[chairId];
  }
};

const rerenderTableChairs = (tableId: TableId) => {
  $("#" + tableId + " .chair").remove();
  pruneChairNumbers();
  for (const chairSpot of chairSpotsOfTable(tableId)) renderChairDom(chairSpot);
  updateDisplayNumbers(tableId);
  for (const guestId of objectKeys(placement)) {
    const chairId = placement[guestId];
    if (allChairSpots[chairId]?.tableId === tableId) renderGuestBallDom(guestId, chairId);
  }
  if (roomMode === "placementMode") setRoomMode("placementMode");
};

const updateDisplayNumbers = (tableId: TableId) => {
  const chairs = chairSpotsOfTable(tableId);
  if (chairs.length === 0) return;
  const numbers = computeTableChairNumbers(tableId);
  for (const chairSpot of chairs) {
    const { chairId } = chairSpot;
    const displayNr = numbers[chairId];
    if (displayNr !== undefined) {
      $("#" + chairId + " .chairLabel").html(displayNr.toString());
      chairNumbers[chairId] = displayNr;
    } else {
      delete chairNumbers[chairId];
      const table = allTables[chairSpot.tableId];
      const color = getColor(table.colorToken);
      $("#" + chairId + " .chairLabel").html(
        `<span class="noChair" style="color: ${color}">+</span>`,
      );
    }
  }
};

const removeChairFromPlacement = (removeChairId: ChairId) => {
  for (let guestId of objectKeys(placement)) {
    const chairId = placement[guestId];
    if (chairId === removeChairId) {
      delete placement[guestId];
      break;
    }
  }
  updatePlacementInfo();
};

const removeChairFromPreferences = (chairId: ChairId) => {
  for (let guestId of objectKeys(allGuests)) {
    const guest = allGuests[guestId];
    const allowed = guest.allowedChairsByRoom[currentRoomId];
    if (allowed) {
      const i = allowed.indexOf(chairId);
      if (i >= 0) allowed.splice(i, 1);
    }
    const notAllowed = guest.notAllowedChairsByRoom[currentRoomId];
    if (notAllowed) {
      const i = notAllowed.indexOf(chairId);
      if (i >= 0) notAllowed.splice(i, 1);
    }
  }
  for (let groupId of objectKeys(allGroups)) {
    const group = allGroups[groupId];
    const allowed = group.allowedChairsByRoom[currentRoomId];
    if (allowed) {
      const i = allowed.indexOf(chairId);
      if (i >= 0) allowed.splice(i, 1);
    }
    const notAllowed = group.notAllowedChairsByRoom[currentRoomId];
    if (notAllowed) {
      const i = notAllowed.indexOf(chairId);
      if (i >= 0) notAllowed.splice(i, 1);
    }
  }
};

const applyChairIdRenames = (renames: { [oldChairId: ChairId]: ChairId }) => {
  for (let guestId of objectKeys(allGuests)) {
    const guest = allGuests[guestId];
    const allowed = guest.allowedChairsByRoom[currentRoomId];
    if (allowed) guest.allowedChairsByRoom[currentRoomId] = allowed.map((id) => renames[id] ?? id);
    const notAllowed = guest.notAllowedChairsByRoom[currentRoomId];
    if (notAllowed)
      guest.notAllowedChairsByRoom[currentRoomId] = notAllowed.map((id) => renames[id] ?? id);
  }
  for (let groupId of objectKeys(allGroups)) {
    const group = allGroups[groupId];
    const allowed = group.allowedChairsByRoom[currentRoomId];
    if (allowed) group.allowedChairsByRoom[currentRoomId] = allowed.map((id) => renames[id] ?? id);
    const notAllowed = group.notAllowedChairsByRoom[currentRoomId];
    if (notAllowed)
      group.notAllowedChairsByRoom[currentRoomId] = notAllowed.map((id) => renames[id] ?? id);
  }
};

const deleteChairSpot = (chairId: ChairId) => {
  removeChairFromPlacement(chairId);
  removeChairFromPreferences(chairId);
  delete allChairSpots[chairId];
  delete chairNumbers[chairId];
};

// A chair's colour in preference mode: red = must not sit here, green = may
// only sit on one of the green chairs, grey = no opinion.
type ChairPreferenceState = "grey" | "red" | "green";

// The guest or group whose preferences are being edited, with its chair lists
// for the current room ready to push to. Undefined outside preference mode.
const getPreferenceSubject = (): Guest | Group | undefined => {
  const guestId = getHighlightedGuestId();
  if (!guestId && !selectedGroupId) return undefined;

  const guestOrGroup = selectedGroupId ? allGroups[selectedGroupId] : allGuests[guestId!];
  if (!guestOrGroup.allowedChairsByRoom[currentRoomId])
    guestOrGroup.allowedChairsByRoom[currentRoomId] = [];
  if (!guestOrGroup.notAllowedChairsByRoom[currentRoomId])
    guestOrGroup.notAllowedChairsByRoom[currentRoomId] = [];
  return guestOrGroup;
};

const getChairPreferenceState = (
  chairId: ChairId,
  allowedChairs: ChairId[],
  notAllowedChairs: ChairId[],
): ChairPreferenceState => {
  if (notAllowedChairs.includes(chairId)) return "red";
  if (allowedChairs.includes(chairId)) return "green";
  return "grey";
};

const setChairPreferenceState = (
  chairId: ChairId,
  state: ChairPreferenceState,
  allowedChairs: ChairId[],
  notAllowedChairs: ChairId[],
) => {
  const removeFrom = (list: ChairId[]) => {
    const i = list.indexOf(chairId);
    if (i !== -1) list.splice(i, 1);
  };
  removeFrom(allowedChairs);
  removeFrom(notAllowedChairs);
  if (state === "red") notAllowedChairs.push(chairId);
  if (state === "green") allowedChairs.push(chairId);

  const color =
    state === "red" ? "var(--red)" : state === "green" ? "var(--green)" : "var(--greySemi)";
  $("#" + chairId + " .chairContent").css("border-color", color);
};

// One chair: grey -> red -> green -> grey.
const toggleChairPreference = (chairId: ChairId) => {
  if (!allChairSpots[chairId].isChair) return;
  const subject = getPreferenceSubject();
  if (!subject) return;
  const allowedChairs = subject.allowedChairsByRoom[currentRoomId];
  const notAllowedChairs = subject.notAllowedChairsByRoom[currentRoomId];

  const state = getChairPreferenceState(chairId, allowedChairs, notAllowedChairs);
  const next: ChairPreferenceState = state === "grey" ? "red" : state === "red" ? "green" : "grey";
  setChairPreferenceState(chairId, next, allowedChairs, notAllowedChairs);

  updateAllowedChairsInfo(allowedChairs, notAllowedChairs);
  updatePreferenceList();
};

// A whole table: all its chairs red, then all green, then all grey. A table
// whose chairs disagree (some flipped one by one) starts over at red, so a
// click always leaves the table in one colour.
const cycleTablePreference = (tableId: TableId) => {
  const subject = getPreferenceSubject();
  if (!subject) return;
  const chairIds = Object.values(allChairSpots)
    .filter((chair) => chair.tableId === tableId && chair.isChair)
    .map((chair) => chair.chairId);
  if (chairIds.length === 0) return;
  const allowedChairs = subject.allowedChairsByRoom[currentRoomId];
  const notAllowedChairs = subject.notAllowedChairsByRoom[currentRoomId];

  const states = new Set(
    chairIds.map((chairId) => getChairPreferenceState(chairId, allowedChairs, notAllowedChairs)),
  );
  const uniform = states.size === 1 ? [...states][0] : undefined;
  const next: ChairPreferenceState =
    uniform === "red" ? "green" : uniform === "green" ? "grey" : "red";
  for (const chairId of chairIds) {
    setChairPreferenceState(chairId, next, allowedChairs, notAllowedChairs);
  }

  updateAllowedChairsInfo(allowedChairs, notAllowedChairs);
  updatePreferenceList();
};

const updateAllowedChairsInfo = (allowedChairs: ChairId[], notAllowedChairs: ChairId[]) => {
  const allowedChairsArr: { table: string; number: number }[] = [];
  for (let chairId of allowedChairs) {
    const chair = allChairSpots[chairId];
    if (chair.isChair) {
      const table = allTables[chair.tableId];
      allowedChairsArr.push({ table: table.label, number: chairNumbers[chairId] });
    }
  }

  const notAllowedChairsArr: { table: string; number: number }[] = [];
  for (let chairId of notAllowedChairs) {
    const chair = allChairSpots[chairId];
    if (chair.isChair) {
      const table = allTables[chair.tableId];
      notAllowedChairsArr.push({ table: table.label, number: chairNumbers[chairId] });
    }
  }

  allowedChairsArr.sort((a, b) => {
    if (a.table === b.table) return a.number - b.number;
    return a.table > b.table ? 1 : -1;
  });

  notAllowedChairsArr.sort((a, b) => {
    if (a.table === b.table) return a.number - b.number;
    return a.table > b.table ? 1 : -1;
  });

  if (allowedChairsArr.length > 0) $(".onlyAllowedChairsHelp").hide();
  else $(".onlyAllowedChairsHelp").show();
  $(".onlyAllowedChairs").html(
    allowedChairsArr.length > 0
      ? allowedChairsArr.map((a) => a.table + " " + a.number).join(", ")
      : "",
  );

  if (notAllowedChairsArr.length > 0) $(".notAllowedChairsHelp").hide();
  else $(".notAllowedChairsHelp").show();
  $(".notAllowedChairs").html(
    notAllowedChairsArr.length > 0
      ? notAllowedChairsArr.map((a) => a.table + " " + a.number).join(", ")
      : "",
  );
};
