// Builds the DOM node for an already-created Table (allTables[tableId] must already
// be set). Used both by the add*Table functions right after minting a new table, and
// by switchRoom to rehydrate a room's existing tables without minting new ones.
const renderTableDom = (table: Table) => {
  const { tableId, type, label, colorToken, centerX, centerY, width, height, rotate } = table;
  const color = getColor(colorToken);
  const transform = rotateTransform(rotate);
  const adjustRotation = rotateTransform(-rotate);

  if (type === "square") {
    $("#room").append(`
      <div
        class="table squareTable"
        id="${tableId}"
        style="top: ${centerY}px; left: ${centerX}px; width: ${width}px; height: ${height}px; transform: ${transform}">
        <div class="tableContent" style="border-color: ${color}"></div>

        <p class="tableLabel adjustRotation" style="transform: ${adjustRotation}">${label}</p>

        <div class="rotateHandle"></div>

        <div class="moveHandle"></div>

        <div class="topBorderResize resizeHandle"></div>
        <div class="leftBorderResize resizeHandle"></div>
        <div class="bottomBorderResize resizeHandle"></div>
        <div class="rightBorderResize resizeHandle"></div>

        <div class="topLeftResize cornerResize resizeHandle"></div>
        <div class="topRightResize cornerResize resizeHandle"></div>
        <div class="bottomLeftResize cornerResize resizeHandle"></div>
        <div class="bottomRightResize cornerResize resizeHandle"></div>
      </div>
    `);
  } else if (type === "round") {
    $("#room").append(`
      <div
        class="table roundTable"
        id="${tableId}"
        style="top: ${centerY}px; left: ${centerX}px; width: ${width}px; height: ${height}px; transform: ${transform}">
        <div class="tableContent" style="border-color: ${color}"></div>

        <p class="tableLabel adjustRotation" style="transform: ${adjustRotation}">${label}</p>

        <div class="rotateHandle"></div>

        <div class="roundResize resizeHandle"></div>

        <div class="moveHandle"></div>

        <div class="roundReshape resizeHandle" style="border-color: ${color}"></div>
      </div>
    `);
  } else if (type === "bench") {
    $("#room").append(`
      <div
        class="table benchTable"
        id="${tableId}"
        style="top: ${centerY}px; left: ${centerX}px; width: ${width}px; height: ${height}px; transform: ${transform}">
        <div class="tableContent" style="border-color: ${color}">
          <div class="benchTopBorder"></div>
        </div>

        <p class="tableLabel adjustRotation" style="transform: ${adjustRotation}">${label}</p>

        <div class="rotateHandle"></div>

        <div class="moveHandle"></div>

        <div class="leftBenchResize resizeHandle" style="border-color: ${color}"></div>
        <div class="rightBenchResize resizeHandle" style="border-color: ${color}"></div>
      </div>
    `);
  }
};

// Brings an existing table's element in line with its data (position,
// size, rotation, label, colour, stacking) — the counterpart to
// renderTableDom for a table that is already on screen. Chairs are not
// touched; a size change needs rerenderTableChairs (chairs.ts) after this.
const updateTableDom = (table: Table) => {
  const { tableId, label, colorToken, centerX, centerY, width, height, rotate, zIndex } = table;
  const element = $("#" + tableId);
  if (element.length === 0) return;
  element.css({
    left: centerX + "px",
    top: centerY + "px",
    width: width + "px",
    height: height + "px",
    transform: rotateTransform(rotate),
  });
  $("#" + tableId + " .adjustRotation").css("transform", rotateTransform(-rotate));
  $("#" + tableId + " .tableLabel").html(label);
  paintTableColor(tableId, colorToken);
  // In preference mode chairs are neutral until coloured for the guest's
  // allowed/forbidden lists (setGuestPreferenceMode), not the table's colour.
  if (roomMode === "preferenceMode") {
    $("#" + tableId + " .chairContent")
      .css("border-color", "var(--greySemi)")
      .css("background", "");
  }
  if (!isSelectedTable(tableId)) element.css("z-index", zIndex);
  tableDomUpdatedListener?.(tableId);
};

const addSquareTable = ({
  label: labelFromProps,
  colorToken: colorTokenFromProps,
  centerX,
  centerY,
  width = boxSize * 3,
  height = boxSize * 3,
  rotate = 0,
  withGrab,
  addDefaultChairs,
}: {
  label?: string;
  colorToken?: ColorToken;
  centerX: number;
  centerY: number;
  width?: number;
  height?: number;
  rotate?: number;
  withGrab?: boolean;
  addDefaultChairs?: boolean;
}) => {
  const nr = allRooms[currentRoomId].nextTableNumber;
  const label = labelFromProps ?? String.fromCharCode(nr + 65);
  const tableId = mintId<TableId>("table");
  const colorToken = colorTokenFromProps ?? nextTableColor ?? colorMap[nr % colorMap.length];
  const table: Table = {
    tableId,
    type: "square",
    label,
    colorToken,
    zIndex: nr,

    centerX,
    centerY,
    width,
    height,
    rotate,
  };
  allTables[tableId] = table;
  renderTableDom(table);

  if (addDefaultChairs) {
    addChairSpot(tableId, "top", 1);
    addChairSpot(tableId, "right", 1);
    addChairSpot(tableId, "bottom", 1);
    addChairSpot(tableId, "left", 1);
  }

  allRooms[currentRoomId].nextTableNumber++;

  if (withGrab) {
    draggableSelector = $("#" + tableId);
  }

  updateAllTablesInfo();
  updatePlacementInfo();
  selectOneTable(tableId);

  setRoomMode("buildMode");

  return tableId;
};

const addRectangleTable = (centerX: number, centerY: number, withGrab?: boolean) => {
  const tableId = addSquareTable({ centerX, centerY, width: 175, withGrab });
  // Three chairs along each long side; the short ends start as empty spots.
  for (const chairNr of [1, 2, 3]) {
    addChairSpot(tableId, "top", chairNr);
    addChairSpot(tableId, "bottom", chairNr);
  }
  addChairSpot(tableId, "left", 1, false);
  addChairSpot(tableId, "right", 1, false);
  updateAllTablesInfo();
  updatePlacementInfo();
  selectOneTable(tableId);
};

const addRoundTable = ({
  label: labelFromProps,
  colorToken: colorTokenFromProps,
  centerX,
  centerY,
  width = 95.493,
  height = 95.493,
  rotate = 0,
  withGrab,
  addDefaultChairs,
}: {
  label?: string;
  colorToken?: ColorToken;
  centerX: number;
  centerY: number;
  width?: number;
  height?: number;
  rotate?: number;
  withGrab?: boolean;
  addDefaultChairs?: boolean;
}) => {
  const nr = allRooms[currentRoomId].nextTableNumber;
  const label = labelFromProps ?? String.fromCharCode(nr + 65);
  const tableId = mintId<TableId>("table");
  const colorToken = colorTokenFromProps ?? nextTableColor ?? colorMap[nr % colorMap.length];
  const table: Table = {
    tableId,
    type: "round",
    label,
    colorToken,
    zIndex: nr,

    centerY,
    centerX,
    height,
    width,
    rotate,
  };
  allTables[tableId] = table;
  renderTableDom(table);

  if (addDefaultChairs) {
    addChairSpot(tableId, "round", 1);
    addChairSpot(tableId, "round", 2);
    addChairSpot(tableId, "round", 3);
    addChairSpot(tableId, "round", 4);
    addChairSpot(tableId, "round", 5);
    addChairSpot(tableId, "round", 6);
  }
  allRooms[currentRoomId].nextTableNumber++;

  if (withGrab) {
    draggableSelector = $("#" + tableId);
  }

  updateAllTablesInfo();
  updatePlacementInfo();
  selectOneTable(tableId);

  setRoomMode("buildMode");

  return tableId;
};

const addOvalTable = (centerX: number, centerY: number, withGrab?: boolean) => {
  addRoundTable({ centerX, centerY, width: 117, height: 70.51, withGrab, addDefaultChairs: true });
};

const addBenchTable = ({
  label: labelFromProps,
  colorToken: colorTokenFromProps,
  centerX,
  centerY,
  width = boxSize * 7,
  height = boxSize,
  rotate = 0,
  withGrab,
  addDefaultChairs,
}: {
  label?: string;
  colorToken?: ColorToken;
  centerX: number;
  centerY: number;
  width?: number;
  height?: number;
  rotate?: number;
  withGrab?: boolean;
  addDefaultChairs?: boolean;
}) => {
  const nr = allRooms[currentRoomId].nextTableNumber;
  const label = labelFromProps ?? String.fromCharCode(nr + 65);
  const tableId = mintId<TableId>("table");
  const colorToken = colorTokenFromProps ?? nextTableColor ?? colorMap[nr % colorMap.length];
  const table: Table = {
    tableId,
    type: "bench",
    label,
    colorToken,
    zIndex: nr,

    centerY,
    centerX,
    width,
    height,
    rotate,
  };
  allTables[tableId] = table;
  renderTableDom(table);

  if (addDefaultChairs) {
    addChairSpot(tableId, "top", 1);
    addChairSpot(tableId, "top", 2);
    addChairSpot(tableId, "top", 3);
  }

  allRooms[currentRoomId].nextTableNumber++;

  if (withGrab) {
    draggableSelector = $("#" + tableId);
  }

  updateAllTablesInfo();
  updatePlacementInfo();
  selectOneTable(tableId);

  setRoomMode("buildMode");

  return tableId;
};

const selectOneTable = (tableId: TableId) => {
  unselectAllGuests();
  unselectAllTables();
  updateAllGuestList();
  selectTables([tableId]);
};

const unselectAllTables = () => {
  selectedTables = [];
  selectedTablesHasBeenUpdated();
};

const unselectOneTable = (tableId: TableId) => {
  const tableIndex = selectedTables.findIndex((t) => t.tableId === tableId);
  if (tableIndex >= 0) {
    selectedTables.splice(tableIndex, 1);
    selectedTablesHasBeenUpdated();
  }
};

const selectTables = (tableIds: TableId[]) => {
  let changed = false;
  for (let tableId of tableIds) {
    if (!isSelectedTable(tableId)) {
      const table = allTables[tableId];
      selectedTables.push({
        tableId,
        startCenterX: table.centerX,
        startCenterY: table.centerY,
        startRotation: table.rotate,
      });
      changed = true;
    }
  }
  if (changed) selectedTablesHasBeenUpdated();
};

const selectedTablesHasBeenUpdated = () => {
  for (let tableId of objectKeys(allTables)) {
    if (isSelectedTable(tableId)) {
      const colorToken = allTables[tableId].colorToken;
      const colorLight = getLightColor(colorToken);
      $("#" + tableId)
        .css("z-index", 950)
        .addClass("highlightedTable");
      removeNotHighlightedStyle(tableId);
      addHighlightedStyle(tableId);

      $("#" + tableId + " .tableContent").css("background", colorLight);
      $("#tableInfoButton_" + tableId).css("background", colorLight);

      if (roomMode === "placementMode") {
        let guestsAtTable: GuestId[] = [];
        for (let guestId of objectKeys(placement)) {
          const table = getGuestTable(guestId);
          if (table && table.tableId === tableId) {
            guestsAtTable.push(guestId);
          }
        }
        selectGuests(guestsAtTable);
      }
    } else {
      $("#" + tableId)
        .css("z-index", allTables[tableId].zIndex)
        .removeClass("highlightedTable");
      removeHighlightedStyle(tableId);

      if (selectedTables.length === 0) {
        removeNotHighlightedStyle(tableId);
      } else {
        addNotHighlightedStyle(tableId);
      }

      $("#" + tableId + " .tableContent").css("background", "");

      $("#tableInfoButton_" + tableId).css("background", "");

      if (roomMode === "placementMode") {
        for (let guestId of objectKeys(placement)) {
          const table = getGuestTable(guestId);
          if (table && table.tableId === tableId) {
            unselectOneGuest(guestId);
          }
        }
      }
    }
  }
  selectionChangedListener?.();
};

const addHighlightedStyle = (tableId: TableId) => {
  const colorToken = allTables[tableId].colorToken;
  const colorDark = getDarkColor(colorToken);
  $("#" + tableId + " .tableContent").css("border-color", colorDark);
  $("#" + tableId + " .chairContent").css("border-color", colorDark);
  $("#" + tableId + " .roundReshape").css("border-color", colorDark);
  $("#" + tableId + " .leftBenchResize").css("border-color", colorDark);
  $("#" + tableId + " .rightBenchResize").css("border-color", colorDark);
};
const removeHighlightedStyle = (tableId: TableId) => {
  const colorToken = allTables[tableId].colorToken;
  const color = getColor(colorToken);
  const colorLight = getLightColor(colorToken);
  $("#" + tableId + " .tableContent").css("border-color", color);
  $("#" + tableId + " .chairContent")
    .css("border-color", color)
    .css("background", colorLight);
  $("#" + tableId + " .roundReshape").css("border-color", color);
  $("#" + tableId + " .leftBenchResize").css("border-color", color);
  $("#" + tableId + " .rightBenchResize").css("border-color", color);
};

const addNotHighlightedStyle = (tableId: TableId) => {
  const colorToken = allTables[tableId].colorToken;
  const colorSemi = getSemiColor(colorToken);
  $("#" + tableId + " .tableContent").css("border-color", colorSemi);
  $("#" + tableId + " .chairContent").css("border-color", colorSemi);
  $("#" + tableId + " .roundReshape").css("border-color", colorSemi);
  $("#" + tableId + " .leftBenchResize").css("border-color", colorSemi);
  $("#" + tableId + " .rightBenchResize").css("border-color", colorSemi);
};
const removeNotHighlightedStyle = (tableId: TableId) => {
  const colorToken = allTables[tableId].colorToken;
  const color = getColor(colorToken);
  $("#" + tableId + " .tableContent").css("border-color", color);
  $("#" + tableId + " .chairContent").css("border-color", color);
  $("#" + tableId + " .roundReshape").css("border-color", color);
  $("#" + tableId + " .leftBenchResize").css("border-color", color);
  $("#" + tableId + " .rightBenchResize").css("border-color", color);
};

const isSelectedTable = (tableId: TableId | undefined) => {
  if (tableId === undefined) return false;
  return selectedTables.some((t) => t.tableId === tableId);
};

// "Table order" means one thing across the app (this list, the export's
// pages and guest lists): alphabetical by label, tie-broken by creation
// order, which is the number in the id. Purely numeric labels compare as
// numbers (2 before 10) and sort ahead of all other labels, which keeps the
// ordering consistent when numeric and text labels are mixed.
const compareTablesByLabel = (a: Table, b: Table): number => {
  const labelA = a.label.trim().toLowerCase();
  const labelB = b.label.trim().toLowerCase();
  const isNumberA = /^\d+$/.test(labelA);
  const isNumberB = /^\d+$/.test(labelB);
  if (isNumberA !== isNumberB) return isNumberA ? -1 : 1;
  const numberDiff = isNumberA ? Number(labelA) - Number(labelB) : 0;
  if (numberDiff !== 0) return numberDiff;
  if (labelA === labelB || isNumberA) {
    return (idNumber(a.tableId, "table_") ?? 0) - (idNumber(b.tableId, "table_") ?? 0);
  }
  return labelA > labelB ? 1 : -1;
};

// Stacking follows the table list: later in the list paints on top. Selected
// tables stay above everything (see selectedTablesHasBeenUpdated) until
// deselected, so only the stored value is updated for them.
const updateTableZIndexes = (sortedTables: Table[]) => {
  sortedTables.forEach((table, i) => {
    table.zIndex = i + 1;
    if (!isSelectedTable(table.tableId)) $("#" + table.tableId).css("z-index", table.zIndex);
  });
};

const updateAllTablesInfo = () => {
  let html = "";
  let tables = [];
  for (let id of objectKeys(allTables)) {
    tables.push(allTables[id]);
  }
  tables.sort(compareTablesByLabel);
  updateTableZIndexes(tables);

  const chairs = [];
  for (let id of objectKeys(allChairSpots)) {
    chairs.push(allChairSpots[id]);
  }

  if (tables.length === 0) {
    $(".tablesContent").hide();
  } else {
    $(".tablesContent").show();
  }

  let totalNrOfChairs = 0;
  for (let table of tables) {
    const isSelected = isSelectedTable(table.tableId);

    const colorToken = table.colorToken;
    const colorLight = getLightColor(colorToken);

    const nrOfChairs = chairs.filter(
      (chair) => chair.tableId === table.tableId && chair.isChair,
    ).length;
    html += `
      <div
        class="tableInfoButton"
        id="tableInfoButton_${table.tableId}"
        onmousedown="onTableRowMouseDown(event, '${table.tableId}')"
        onclick="onTableRowClick(event, '${table.tableId}')"
        style="${isSelected ? "background: " + colorLight : ""}">
        <input
          id="input_${table.tableId}"
          class="tableInput"
          type="text"
          value="${table.label}"
          onfocus="selectOneTable('${table.tableId}')"
          oninput="updateTableName('${table.tableId}', this.value)"
          onblur="onTableInputBlur()">
        <div id="tableRowColorSelector_${table.tableId}" class="tableRowColorSelector" onclick="event.stopPropagation()" onmousedown="event.preventDefault()"></div>
        <div class="rowIconButton" onclick="event.stopPropagation(); removeTable('${table.tableId}')" onmousedown="event.preventDefault()" title="${t("tables.deleteTable")}">
          <svg
            class="smallIcon"
            width="24"
            height="24"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round">
            <path d="M3 6h18"></path>
            <path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"></path>
            <path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"></path>
            <line x1="10" x2="10" y1="11" y2="17"></line>
            <line x1="14" x2="14" y1="11" y2="17"></line>
          </svg>
        </div>
      </div>`;
    totalNrOfChairs += nrOfChairs;
  }

  $("#totalNrOfChairs").html("" + totalNrOfChairs);
  $("#allTables").html(html + (tables.length > 0 ? "<br>" : ""));
  listsRenderedListener?.();

  for (let table of tables) {
    const selector = getTableRowColorSelector(table.tableId);
    selector.mount("#tableRowColorSelector_" + table.tableId);
    selector.setValue(colorOptions.find((o) => o.value === table.colorToken)!);
  }
};

// Shift/Cmd-click on a row toggles it in the selection, like clicking tables in
// the room. It's decided on mousedown, not click: pressing a row's label input
// focuses it, and that focus handler selects only that table. preventDefault
// keeps the focus (and its select-one) from happening on a modifier press.
const isTableRowModifierEvent = (event: MouseEvent) => event.shiftKey || event.metaKey;

const onTableRowMouseDown = (event: MouseEvent, tableId: TableId) => {
  if (!isTableRowModifierEvent(event)) return;
  const target = event.target as Element;
  if (target.closest(".tableRowColorSelector, .rowIconButton")) return;
  event.preventDefault();
  if (isSelectedTable(tableId)) unselectOneTable(tableId);
  else selectTables([tableId]);
};

const onTableRowClick = (event: MouseEvent, tableId: TableId) => {
  if (isTableRowModifierEvent(event)) return;
  selectOneTable(tableId);
};

// Blur handler for the table-list label inputs. Leaving an input re-sorts the
// list (labels drive the sort order), but rebuilding #allTables mid-click
// would destroy the element the user is clicking into, swallowing the click.
// So wait a tick for focus to settle, and skip the rebuild entirely while
// focus is anywhere in the list (Tab moves it straight to the next label
// input; the rows' colour buttons are out of the Tab order) — the list
// re-sorts once the user leaves it. The rows' colour and delete controls
// additionally preventDefault on mousedown so clicking them never blurs the
// input in the first place.
const onTableInputBlur = () => {
  setTimeout(() => {
    const list = document.getElementById("allTables");
    if (list && document.activeElement && list.contains(document.activeElement)) return;
    updateAllTablesInfo();
  });
};

const removeTable = (tableId: TableId) => {
  recordHistory();
  for (let chairId of objectKeys(allChairSpots)) {
    const chair = allChairSpots[chairId];
    if (chair.tableId === tableId) {
      deleteChairSpot(chairId);
    }
  }
  delete allTables[tableId];
  $("#" + tableId).remove();
  unselectAllTables();
  unselectAllGuests();
  updateAllTablesInfo();
  updateAllGuestList();
  updatePlacementInfo();
};

const updateTableName = (tableId: TableId, text: string) => {
  const newName = replaceTags(text.trim());
  if (allTables[tableId].label === newName) return;

  recordHistoryCoalesced("tableName:" + tableId);
  allTables[tableId].label = newName;
  $("#" + tableId + " .tableLabel").html(newName);
  updateTableZIndexes(
    objectKeys(allTables)
      .map((id) => allTables[id])
      .sort(compareTablesByLabel),
  );
  updatePreferenceList();
};
