const createRoom = (roomName?: string): RoomId => {
  const roomId = mintId<RoomId>("room");

  const room: Room = {
    roomId,
    roomName: roomName ?? t("rooms.defaultName", { number: roomOrder.length + 1 }),
    tables: {},
    chairSpots: {},
    placement: {},
    zoom: 1,
    scrollLeft: (BASE_ROOM_SIZE - roomScrollable.clientWidth) / 2,
    scrollTop: (BASE_ROOM_SIZE - roomScrollable.clientHeight) / 2,
    nextTableNumber: 0,
  };
  allRooms[roomId] = room;
  roomOrder.push(roomId);
  return roomId;
};

// Rebuilds a room's table/chair DOM from its stored data, without minting new
// ids — the counterpart to switchRoom clearing #room via clearRoomCanvasDom.
const renderRoomDom = (room: Room) => {
  for (let tableId of objectKeys(room.tables)) {
    renderTableDom(room.tables[tableId]);
  }
  for (let chairId of objectKeys(room.chairSpots)) {
    renderChairDom(room.chairSpots[chairId]);
  }
  // renderChairDom only builds the chair's DOM node — the actual "1", "2", ...
  // label text is filled in by updateDisplayNumbers, same as addChairSpot does
  // per-chair on the build path.
  for (let tableId of objectKeys(room.tables)) {
    updateDisplayNumbers(tableId);
  }
  // Guest balls are DOM, not data — placement itself survives the rebind in
  // switchRoom untouched, but the chair DOM it points at was just torn down
  // and rebuilt above, so the balls need to be rebuilt too.
  for (let guestId of objectKeys(room.placement)) {
    renderGuestBallDom(guestId, room.placement[guestId]);
  }
  updateChairGuestBallNames();

  if (roomMode === "preferenceMode") {
    if (selectedGroupId) {
      setGroupPreferenceMode(selectedGroupId);
    } else {
      const selectedGuestId = getHighlightedGuestId();
      if (selectedGuestId) setGuestPreferenceMode(selectedGuestId);
    }
  }
  if (roomMode === "placementMode") setRoomMode("placementMode");
};

// Writes the live viewport (zoom + scroll) back into the given room's data —
// rooms only sync it when they stop being the on-screen one, so both
// switchRoom (outgoing room) and persistence saves (active room) need this.
const captureRoomViewport = (room: Room) => {
  room.zoom = currentScale;
  room.scrollLeft = roomScrollable.scrollLeft;
  room.scrollTop = roomScrollable.scrollTop;
};

// Makes a room the live one: rebinds the shared allTables/allChairSpots/
// placement references, rebuilds #room's DOM from its data, and applies its
// viewport. Shared by initRooms, switchRoom, and the persistence restore;
// callers handle their own teardown of selection/drag state first.
const activateRoom = (room: Room) => {
  allTables = room.tables;
  allChairSpots = room.chairSpots;
  placement = room.placement;
  currentRoomId = room.roomId;

  clearRoomCanvasDom();
  renderRoomDom(room);
  applyRoomZoomAndScroll(room.zoom, room.scrollLeft, room.scrollTop);
  roomActivatedListener?.();
};

// Told after every room activation (presence.ts redraws what the others
// are doing in the room now on show). A seam, not a call: presence.ts
// loads after this file, and the first activation runs at load.
let roomActivatedListener: (() => void) | undefined;

const switchRoom = (roomId: RoomId) => {
  if (roomId === currentRoomId) return;
  const newRoom = allRooms[roomId];
  if (!newRoom) return;

  const outgoingRoom = allRooms[currentRoomId];
  if (outgoingRoom) captureRoomViewport(outgoingRoom);

  // Selection/drag state below all reference TableId/ChairId DOM nodes that are
  // about to be torn down; guest/group selection stays untouched since guests
  // are shared across rooms.
  unselectAllTables();
  if (roomMode !== "preferenceMode") unselectAllGuests();
  draggableSelector = undefined;
  resizeSelector = undefined;
  rotateSelector = undefined;
  if (guestBallSelectorType === "Chair" && guestBallSelector) {
    guestBallSelector.remove();
    guestBallSelector = undefined;
  }
  activeResize = { ns: "", ew: "", type: "square" };

  activateRoom(newRoom);

  updateAllTablesInfo();
  updateAllGuestList();
  updatePlacementInfo();
  updateRoomTabs();
};

const addRoom = () => {
  recordHistory();
  const roomId = createRoom();
  switchRoom(roomId);
};

const deleteRoom = (roomId: RoomId) => {
  if (roomOrder.length <= 1) return;
  const index = roomOrder.indexOf(roomId);
  if (index < 0) return;

  const wasActive = roomId === currentRoomId;

  recordHistory();
  roomOrder.splice(index, 1);
  delete allRooms[roomId];

  for (let guestId of objectKeys(allGuests)) {
    delete allGuests[guestId].allowedChairsByRoom[roomId];
    delete allGuests[guestId].notAllowedChairsByRoom[roomId];
  }
  for (let groupId of objectKeys(allGroups)) {
    delete allGroups[groupId].allowedChairsByRoom[roomId];
    delete allGroups[groupId].notAllowedChairsByRoom[roomId];
  }

  if (wasActive) {
    const nextRoomId = roomOrder[Math.min(index, roomOrder.length - 1)];
    switchRoom(nextRoomId);
  } else {
    updateRoomTabs();
  }
};

const confirmDeleteRoom = (roomId: RoomId) => {
  const room = allRooms[roomId];
  if (!room) return;

  showConfirmDialog({
    title: t("rooms.deleteTitle"),
    description: t("rooms.deleteDescription", { name: room.roomName }),
    affirmativeLabel: t("rooms.deleteConfirm"),
    onAffirmative: () => deleteRoom(roomId),
    dismissLabel: t("dialog.cancel"),
  });
};

const updateRoomName = (roomId: RoomId, text: string) => {
  const room = allRooms[roomId];
  if (!room) return;
  const newName = replaceTags(text.trim());
  if (room.roomName === newName) return;
  recordHistoryCoalesced("roomName:" + roomId);
  room.roomName = newName;
};

const updateRoomTabs = () => {
  let html = `<div id="roomTabBarButtons">`;
  let i = 0;
  for (let roomId of roomOrder) {
    const room = allRooms[roomId];
    const isActive = roomId === currentRoomId;
    html += `
      <div
        class="roomTabButton blurry ${isActive ? "activeRoomTab" : ""}"
        id="roomTab_${roomId}"
        style="z-index: ${roomOrder.length - i}"
        onmousedown="if ('${roomId}' !== currentRoomId) switchRoom('${roomId}')">
        <input
          id="input_${room.roomId}"
          class="roomTabInput"
          type="text"
          value="${room.roomName}"
          onclick="event.stopPropagation()"
          onkeyup="updateRoomName('${roomId}', this.value)"
          onblur="updateRoomTabs()">
        ${
          roomOrder.length > 1
            ? `<div class="rowIconButton roomTabDeleteIcon" onmousedown="event.stopPropagation(); confirmDeleteRoom('${roomId}')" title="${t("rooms.deleteRoom")}">
                ${crossIcon()}
              </div>`
            : ""
        }
      </div>`;
    i++;
  }

  html += `
    <div class="roomTabButton blurry addRoomButton" onmousedown="addRoom()" title="${t("rooms.newRoom")}">
      ${plusIcon()}
    </div>
  </div>`;

  $("#roomTabBar").html(html);
  listsRenderedListener?.();
};

const initRooms = () => {
  const roomId = createRoom(t("rooms.defaultName", { number: 1 }));
  activateRoom(allRooms[roomId]);
  updateRoomTabs();
};
initRooms();
