// Saved projects: a signed-in person's arrangements in their account
// (api/projects.php). The app still works from localStorage exactly as it
// does for everyone (persistence.ts); for an account holder, every change
// is also sent to the server a few seconds later (and at once when it
// matters: switching project, opening the list, signing out, leaving), and
// the account dialog lists the projects to switch between, rename,
// duplicate and delete. Nothing here runs for anonymous sessions.
//
// One project is "current": the one the arrangement on screen belongs to,
// remembered in localStorage next to the snapshot so a reload knows which
// project it is looking at. Its edits travel as operations (edits.ts)
// through the project's log on the server, and others' come back the same
// way, within seconds (sync.ts) — this file holds the project itself: the
// record, the list and its actions, sharing, the status in the room's
// corner, and the lining up of the copies on load (reconcileProjects:
// signing in with work on screen makes it the account's newest project; a
// pristine session opens the account's latest one).
//
// A project can be shared (api/project-access.php): its owner hands out an
// invite link (the members view in the account dialog), and whoever opens
// it signed in becomes a member — equal for the plan itself, listed under
// "shared with you". Only the owner manages members and deletes.

const PROJECTS_ENDPOINT = "/api/projects.php";
const CURRENT_PROJECT_STORAGE_KEY = "seatingApp.currentProject";
// The snapshot the server is known to hold (the last one saved from here,
// or loaded here): what a merge judges both sides' changes against.
const SYNCED_STATE_STORAGE_KEY = "seatingApp.syncedState";
// An invite link opened before signing in waits here for the sign-in
// (this tab's own: sessionStorage).
const PENDING_JOIN_STORAGE_KEY = "seatingApp.pendingJoin";
// How long the room's corner says that another computer's version was
// taken in (renderProjectsStatus).
const SYNC_NOTICE_MS = 6000;
// How many projects an account holds (api/projects.php's PROJECTS_PER_USER);
// the server's own number replaces it once a refusal has carried it.
let projectsPerAccount = 50;
// The server's size cap for a state, in bytes of its JSON, once a 413 has
// told it (api/project-access.php's PROJECT_MAX_STATE_BYTES). Until then
// every snapshot is sent; after, one known to be over is kept here instead.
let projectStateLimitBytes: number | null = null;

type ProjectSummary = {
  id: string;
  name: string;
  revision: number;
  // The project's log of edits (sync.ts): its head, and the edit the saved
  // state is a checkpoint of.
  headSeq: number;
  stateSeq: number;
  guestCount: number;
  tableCount: number;
  roomCount: number;
  published: boolean;
  // Epoch seconds of the last publish, null when never published; the
  // guests' page address (null until the first publish).
  publishedAt: number | null;
  // The revision that was published: a higher current revision means
  // edits the guests don't see yet.
  publishedRevision: number | null;
  // The rooms guests see (a publish is of the rooms the owner chose); null
  // when never published, or published before publishing was of chosen rooms.
  publishedRoomIds: RoomId[] | null;
  guestUrl: string | null;
  // Until when (epoch seconds) the guests' page is paid for (share.ts);
  // null when never paid. Publishing needs it to lie ahead.
  publishedUntil: number | null;
  // Sharing: whether this account owns the project (else it is a member,
  // let in by the owner's invite link), who the owner is, and how many
  // members it has (for the owner's list).
  isOwner: boolean;
  owner: { name: string; email: string };
  memberCount: number;
  // The owner's free access publishes the project for its members too
  // (share.ts publishesFree).
  ownerFreeAccess: boolean;
  createdAt: number;
  updatedAt: number;
};

// The project the arrangement on screen belongs to. syncedSeq is the last
// edit of the project's log this computer has applied (null for a record
// from before the log: everything is fetched); stateSeq the edit the
// server's saved state is a checkpoint of. owner is the account it belongs
// to, so that a different person signing in on this computer (after a
// session expired) is not handed the previous one's plan. isOwner: whether
// that account owns the project or is a member of it (a member's access
// can end, handleProjectGone).
type CurrentProject = {
  id: string;
  name: string;
  revision: number;
  syncedSeq: number | null;
  stateSeq: number;
  owner: string;
  isOwner: boolean;
  ownerFreeAccess: boolean;
  // How many others share the project: the poll's pace follows it (sync.ts).
  memberCount: number;
  publishedAt: number | null;
  publishedRevision: number | null;
  publishedRoomIds: RoomId[] | null;
  guestUrl: string | null;
  publishedUntil: number | null;
  updatedAt: number;
};

// The server's two standing refusals: a full account (create, duplicate) and
// a state over its size cap (create, save). Unlike a failure they are not
// retried on a timer — the answer would be the same until a project goes
// (the account then has room: retrySaveIfRoomFreed) or the plan is edited
// (it may have shrunk: onLocalSnapshotSaved).
type ProjectRefusal = "limitReached" | "tooLarge";

// "failed" is offline or a server error, retried; the refusals stay until
// a save lands. "updated" and "merged" say that another computer's version
// was just taken in (as it was, or merged with edits made here); they stay
// in the status line until the next edit here.
type ProjectSyncStatus = "saved" | "saving" | "failed" | "updated" | "merged" | ProjectRefusal;

// How a create attempt ended.
type ProjectCreateResult =
  | { outcome: "created"; project: ProjectSummary }
  | { outcome: "refused"; reason: ProjectRefusal }
  | { outcome: "failed" };

let currentProject: CurrentProject | null = null;
let projectList: ProjectSummary[] = [];
// How many of this computer's changes the last merge gave up to theirs
// (merge.ts), for the status line.
let lastMergeOverridden = 0;
// The synced state (readSyncedState) as this tab last wrote it, for when
// localStorage would not take it (a plan near the quota).
let syncedStateInMemory: string | null = null;
// A line above the list after signing in ("saved as …"), once.
let projectsNote: string | null = null;

// The note is for the moment it was written in (the sign-in): gone when the
// dialog closes or another project opens, not only on the next load.
const clearProjectsNote = () => {
  if (projectsNote === null) return;
  projectsNote = null;
  renderProjectsPanel();
};
// Set while reconcileProjects lines this computer up with the account; a
// project found gone meanwhile is handled there, in order, not on its own.
let reconcilingProjects = false;
let projectGoneWhileReconciling: { snapshot: string | null } | null = null;
let projectSyncStatus: ProjectSyncStatus = "saved";
// When "updated" or "merged" was last set: the corner says so for
// SYNC_NOTICE_MS from then (the status itself lasts until the next edit).
let syncNoticeShownAt = 0;
let syncNoticeTimer: number | undefined;
// The refusal the autosave last told the user about in a dialog, so that
// the same answer again (every edit of a too-large plan) is only the status
// line. Cleared when a save lands.
let announcedRefusal: ProjectRefusal | null = null;
let projectCreation: Promise<ProjectCreateResult> | null = null;
// While a server version is being made the live arrangement, what that
// changes is not an edit of ours to send back (sync.ts).
let adoptingServerSnapshot = false;
// While the copies are being lined up (reconcileProjects), nothing is sent.
let projectSyncPaused = false;
// After the current project was deleted here, the arrangement on screen is
// not to be saved as a new one by the next edit; the project opened next
// (adoptServerState) ends this.
let lazyCreateSuppressed = false;
let renamingProjectId: string | null = null;

const accountOwner = (): string => getAccountUser()?.email ?? "";

// Who shares a project, as the list and the dialogs name them: the name,
// or the e-mail when the account has none.
const ownerLabel = (project: ProjectSummary): string => project.owner.name || project.owner.email;

// --- The current project record, next to the snapshot in localStorage ---

const readRoomIds = (value: unknown): RoomId[] | null =>
  Array.isArray(value) && value.every((id) => typeof id === "string" && isSafeId(id))
    ? (value as RoomId[])
    : null;

const readCurrentProjectRecord = (): CurrentProject | null => {
  const raw = readStoredString(CURRENT_PROJECT_STORAGE_KEY);
  if (raw === null) return null;
  try {
    const value: unknown = JSON.parse(raw);
    if (
      !isPlainRecord(value) ||
      typeof value.id !== "string" ||
      typeof value.name !== "string" ||
      typeof value.revision !== "number" ||
      typeof value.owner !== "string"
    ) {
      return null;
    }
    return {
      id: value.id,
      name: value.name,
      revision: value.revision,
      syncedSeq: typeof value.syncedSeq === "number" ? value.syncedSeq : null,
      stateSeq: typeof value.stateSeq === "number" ? value.stateSeq : 0,
      owner: value.owner,
      isOwner: value.isOwner !== false,
      ownerFreeAccess: value.ownerFreeAccess === true,
      memberCount: typeof value.memberCount === "number" ? value.memberCount : 0,
      publishedAt: typeof value.publishedAt === "number" ? value.publishedAt : null,
      publishedRevision:
        typeof value.publishedRevision === "number" ? value.publishedRevision : null,
      publishedRoomIds: readRoomIds(value.publishedRoomIds),
      guestUrl: typeof value.guestUrl === "string" ? value.guestUrl : null,
      publishedUntil: typeof value.publishedUntil === "number" ? value.publishedUntil : null,
      updatedAt: typeof value.updatedAt === "number" ? value.updatedAt : 0,
    };
  } catch {
    return null;
  }
};

const writeCurrentProjectRecord = () => {
  if (currentProject === null) {
    removeStoredString(CURRENT_PROJECT_STORAGE_KEY);
    removeStoredString(SYNCED_STATE_STORAGE_KEY);
    syncedStateInMemory = null;
  } else {
    writeStoredString(CURRENT_PROJECT_STORAGE_KEY, JSON.stringify(currentProject));
  }
  // Every change to the record passes here: the header follows it.
  renderProjectNameHeader();
};

// The server's saved state as far as this browser knows (the checkpoint it
// last laid down or took in): the base a merge judges both sides against
// when this computer fell too far behind the log (merge.ts, sync.ts). Kept
// in localStorage, and in this tab as well for when the storage is full
// (the synced copy doubles what the plan takes). Null when not known.
const readSyncedState = (): string | null =>
  readStoredString(SYNCED_STATE_STORAGE_KEY) ?? syncedStateInMemory;
const writeSyncedState = (serialized: string) => {
  syncedStateInMemory = serialized;
  writeStoredString(SYNCED_STATE_STORAGE_KEY, serialized);
};

// --- Talking to the API ---

type ProjectApiResult = { status: number; data: RawSnapshot | null };

// status 0 = no answer at all (offline). A 401 means the session ended;
// account.ts turns the header back to "Sign in".
const projectApi = async (query: string, body?: object): Promise<ProjectApiResult> => {
  try {
    const response = await fetch(
      PROJECTS_ENDPOINT + query,
      body
        ? {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(body),
          }
        : { cache: "no-store" },
    );
    let data: unknown = null;
    try {
      data = await response.json();
    } catch {
      // A non-JSON answer (a proxy error page) reads as no data.
    }
    if (response.status === 401) handleAccountSessionLost();
    return { status: response.status, data: isPlainRecord(data) ? data : null };
  } catch {
    return { status: 0, data: null };
  }
};

const readProjectSummary = (value: unknown): ProjectSummary | null => {
  if (!isPlainRecord(value)) return null;
  if (typeof value.id !== "string" || typeof value.name !== "string") return null;
  if (typeof value.revision !== "number") return null;
  return {
    id: value.id,
    name: value.name,
    revision: value.revision,
    headSeq: typeof value.headSeq === "number" ? value.headSeq : 0,
    stateSeq: typeof value.stateSeq === "number" ? value.stateSeq : 0,
    guestCount: typeof value.guestCount === "number" ? value.guestCount : 0,
    tableCount: typeof value.tableCount === "number" ? value.tableCount : 0,
    roomCount: typeof value.roomCount === "number" ? value.roomCount : 1,
    published: value.published === true,
    publishedAt: typeof value.publishedAt === "number" ? value.publishedAt : null,
    publishedRevision: typeof value.publishedRevision === "number" ? value.publishedRevision : null,
    publishedRoomIds: readRoomIds(value.publishedRoomIds),
    guestUrl: typeof value.guestUrl === "string" ? value.guestUrl : null,
    publishedUntil: typeof value.publishedUntil === "number" ? value.publishedUntil : null,
    // Absent in an older answer: then it is this account's own.
    isOwner: value.isOwner !== false,
    owner: {
      name:
        isPlainRecord(value.owner) && typeof value.owner.name === "string" ? value.owner.name : "",
      email:
        isPlainRecord(value.owner) && typeof value.owner.email === "string"
          ? value.owner.email
          : "",
    },
    memberCount: typeof value.memberCount === "number" ? value.memberCount : 0,
    ownerFreeAccess: value.ownerFreeAccess === true,
    createdAt: typeof value.createdAt === "number" ? value.createdAt : 0,
    updatedAt: typeof value.updatedAt === "number" ? value.updatedAt : 0,
  };
};

// --- Snapshots as the API sees them ---

const parseSerializedSnapshot = (serialized: string): RawSnapshot => {
  const value: unknown = JSON.parse(serialized);
  return isPlainRecord(value) ? value : {};
};

// Names go into dialog text that is rendered as HTML (confirmDialog.ts);
// the names themselves are plain text.
const nameForDialog = (name: string): string => replaceTags(name);

// The list's counts, from the snapshot being sent.
const countsOf = (
  state: RawSnapshot,
): { guestCount: number; tableCount: number; roomCount: number } => {
  const guestCount = isPlainRecord(state.allGuests) ? Object.keys(state.allGuests).length : 0;
  let tableCount = 0;
  let roomCount = 0;
  if (isPlainRecord(state.allRooms)) {
    for (const roomId of Object.keys(state.allRooms)) {
      roomCount += 1;
      const room = state.allRooms[roomId];
      if (isPlainRecord(room) && isPlainRecord(room.tables)) {
        tableCount += Object.keys(room.tables).length;
      }
    }
  }
  return { guestCount, tableCount, roomCount };
};

// Today in the visitor's own zone as YYYY-MM-DD (toISOString would give
// the UTC date, a day off late in the evening here).
const localDateString = (): string => {
  const now = new Date();
  const pad = (n: number) => String(n).padStart(2, "0");
  return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
};

const datedProjectName = (): string => t("projects.defaultName", { date: localDateString() });

// A new project's name: the couple's names from the export header when
// given, else the date — for the arrangement on screen, or for a state
// about to become a project (a file opened, projectFile.ts).
const projectNameForState = (state: { exportSettings: typeof exportSettings }): string => {
  const names = unescapeTags(state.exportSettings.guestListHeaderNames ?? "").trim();
  return names !== "" ? names : datedProjectName();
};
const defaultProjectName = (): string => projectNameForState({ exportSettings });

// --- Creating and adopting ---

// The server's answer read for a refusal; null for success or a failure.
// A refusal carries the limit it was about, which is kept.
const readProjectRefusal = (status: number, data: RawSnapshot | null): ProjectRefusal | null => {
  if (status === 409 && data?.error === "limit") {
    if (typeof data.limit === "number") projectsPerAccount = data.limit;
    return "limitReached";
  }
  // (An edit over its own cap is sync.ts's to handle, not the state's.)
  if (status === 413 && data?.error === "too_large") {
    if (typeof data.limit === "number") projectStateLimitBytes = data.limit;
    return "tooLarge";
  }
  return null;
};

const showProjectRefusalDialog = (refusal: ProjectRefusal) => {
  if (refusal === "limitReached") {
    showAlertDialog({
      title: t("projects.limitTitle"),
      description: t("projects.limitDescription", { limit: projectsPerAccount }),
    });
  } else {
    showAlertDialog({
      title: t("projects.tooLargeTitle"),
      description: t("projects.tooLargeDescription"),
    });
  }
};

// A save was refused: the status line says so for as long as it holds, the
// dialog once, when it is news. The plan stays here; a later attempt (room
// freed, plan edited smaller) tries again.
const noteProjectSaveRefused = (refusal: ProjectRefusal) => {
  setProjectSyncStatus(refusal);
  if (announcedRefusal === refusal) return;
  announcedRefusal = refusal;
  showProjectRefusalDialog(refusal);
};

const projectSaveRefused = () =>
  projectSyncStatus === "limitReached" || projectSyncStatus === "tooLarge";

// The status line's words for the refusal that stands; null when none does.
// share.ts shows them where a publish or a payment would otherwise fail
// with a generic message.
const projectRefusalText = (): string | null => {
  if (projectSyncStatus === "limitReached") {
    return t("projects.statusLimit", { limit: projectsPerAccount });
  }
  if (projectSyncStatus === "tooLarge") return t("projects.statusTooLarge");
  return null;
};

// Whether a plan the account refused to take as a project is open here:
// this browser holds its only copy, so account.ts does not clear it
// (sign-out, delete account). With a project, a refusal is of the saved
// state alone; the edits themselves are in the log.
const hasUnsavedRefusedPlan = (): boolean => projectSaveRefused() && currentProject === null;

// True when the server is known to refuse a snapshot this large (the cap a
// 413 told of): it is not sent, the status line says so instead. Measured
// as the server does, in bytes of the state's JSON.
const snapshotOverLimit = (serialized: string): boolean => {
  if (projectStateLimitBytes === null) return false;
  const json = JSON.stringify(parseSerializedSnapshot(serialized));
  return new TextEncoder().encode(json).length > projectStateLimitBytes;
};

// A full account was why the plan here could not become a project; with
// fewer projects now (one deleted here or elsewhere), it is tried again.
const retrySaveIfRoomFreed = () => {
  if (
    projectSyncStatus === "limitReached" &&
    projectList.length < projectsPerAccount &&
    currentProject === null
  ) {
    scheduleSync(0);
  }
};

// A project on the server from a snapshot, named; the result says how it
// ended. Nothing is shown here: the caller knows whether a refusal is a
// status line (the autosave) or a dialog (a button pressed).
const createProject = async (serialized: string, name: string): Promise<ProjectCreateResult> => {
  const state = parseSerializedSnapshot(serialized);
  const { status, data } = await projectApi("", {
    action: "create",
    name,
    state,
    ...countsOf(state),
  });
  const refusal = readProjectRefusal(status, data);
  if (refusal !== null) return { outcome: "refused", reason: refusal };
  if (status !== 200 || data === null) return { outcome: "failed" };
  const project = readProjectSummary(data.project);
  return project === null ? { outcome: "failed" } : { outcome: "created", project };
};

// The arrangement on screen becomes a project in the account. One creation
// at a time: the first autosave after signing in and the sign-in flow
// itself must not both make one.
const ensureProjectForSnapshot = (
  serialized: string,
  name: string,
): Promise<ProjectCreateResult> => {
  if (currentProject !== null) return Promise.resolve({ outcome: "failed" });
  if (projectCreation) return projectCreation;
  projectCreation = (async () => {
    try {
      const result = await createProject(serialized, name);
      // Refused (a full account, a plan too large): the plan stays in this
      // browser and waits, the status line says so.
      if (result.outcome === "refused") noteProjectSaveRefused(result.reason);
      if (result.outcome === "created") {
        const created = result.project;
        currentProject = {
          id: created.id,
          name: created.name,
          revision: created.revision,
          syncedSeq: created.headSeq,
          stateSeq: created.stateSeq,
          owner: accountOwner(),
          isOwner: created.isOwner,
          ownerFreeAccess: created.ownerFreeAccess,
          memberCount: created.memberCount,
          publishedAt: created.publishedAt,
          publishedRevision: created.publishedRevision,
          publishedRoomIds: created.publishedRoomIds,
          guestUrl: created.guestUrl,
          publishedUntil: created.publishedUntil,
          updatedAt: created.updatedAt,
        };
        lazyCreateSuppressed = false;
        writeCurrentProjectRecord();
        writeSyncedState(serialized);
        setProjectSyncStatus("saved");
        renderProjectsPanel();
        // Edited while the request was out: that goes on as an edit.
        afterProjectCreated(serialized);
      }
      return result;
    } finally {
      projectCreation = null;
    }
  })();
  return projectCreation;
};

// Makes a server copy the live arrangement: the project becomes current,
// its state replaces what is on screen. Undo starts over only when it is
// another project; a newer version of the same one leaves the stack alone
// (its entries apply only where their fields still match, history.ts).
const adoptServerState = (summary: ProjectSummary, state: PersistedState): boolean => {
  const switchingProject = currentProject?.id !== summary.id;
  // Close the edit in progress; one a gesture left open (the pointer went
  // to another window mid-drag, so no mouseup wrote its data) is dropped
  // rather than diffed against the copy about to replace the state.
  commitEdit();
  discardOpenEdit();
  if (switchingProject) detachPendingEdits();
  currentProject = {
    id: summary.id,
    name: summary.name,
    revision: summary.revision,
    // The state given is the server's saved one, as of stateSeq; the
    // caller applies the log's edits since and moves syncedSeq on.
    syncedSeq: summary.stateSeq,
    stateSeq: summary.stateSeq,
    owner: accountOwner(),
    isOwner: summary.isOwner,
    ownerFreeAccess: summary.ownerFreeAccess,
    memberCount: summary.memberCount,
    publishedAt: summary.publishedAt,
    publishedRevision: summary.publishedRevision,
    publishedRoomIds: summary.publishedRoomIds,
    guestUrl: summary.guestUrl,
    publishedUntil: summary.publishedUntil,
    updatedAt: summary.updatedAt,
  };
  lazyCreateSuppressed = false;
  adoptingServerSnapshot = true;
  let opened: boolean;
  try {
    opened = switchingProject ? openPersistedState(state) : showServerVersion(state);
  } finally {
    adoptingServerSnapshot = false;
  }
  if (!opened) {
    // Half rebuilt; the reload brings the stored arrangement back.
    showAlertDialog({
      title: t("projects.loadFailed"),
      description: "",
      onClose: () => window.location.reload(),
    });
    return false;
  }
  if (switchingProject) clearHistory();
  // What is on screen is the server's, not a change made here (history.ts's
  // look for unrecorded changes must not take it for one, nor sync.ts's
  // for the export settings).
  markArrangementAsKnown();
  markExportSettingsAsKnown();
  // The stored snapshot is now the server's saved state: the base should a
  // merge be needed.
  const stored = readStoredString(PERSISTENCE_STORAGE_KEY);
  if (stored !== null) writeSyncedState(stored);
  writeCurrentProjectRecord();
  setProjectSyncStatus("saved");
  renderProjectsPanel();
  return true;
};

// A newer version of the project on screen: changed on screen only where
// it differs (liveUpdate.ts), so the other person's table move is just that
// table moving here — the selection, the mode and an open preference panel
// stay. The export settings travel with the project too (the names setting
// is published), so they are taken over as well. Falls back to the whole
// replacement if the patch throws (with its own failure path).
const showServerVersion = (state: PersistedState): boolean => {
  if (!persistenceReady) return openPersistedState(state);
  try {
    const readable = readPersistedSnapshot(state) ?? state;
    showArrangement(readable, HISTORY_EDIT_RULES);
    if (JSON.stringify(exportSettings) !== JSON.stringify(readable.exportSettings)) {
      Object.assign(exportSettings, readable.exportSettings);
      syncExportPanelFromSettings();
    }
  } catch (error) {
    console.error("Could not patch in the version from elsewhere, replacing instead:", error);
    const opened = openPersistedState(state);
    // Replaced whole: what is on screen is theirs, not a change made here.
    if (opened) markArrangementAsKnown();
    return opened;
  }
  saveStateNow();
  return true;
};

// --- The status, and the server's answers that end a project here ---

const setProjectSyncStatus = (status: ProjectSyncStatus) => {
  projectSyncStatus = status;
  if (status === "saved") announcedRefusal = null;
  if (status === "updated" || status === "merged") syncNoticeShownAt = Date.now();
  renderProjectsStatus();
};

// A round answered 404 (sync.ts): the server no longer has the project.
// Handled after the round — a member's case opens another project, which
// waits for the request in flight, this one. While the account is being
// lined up (reconcileProjects) the owner's case is handed to it instead, so
// the plan is saved under the account before the list is shown.
const noteProjectGone = (snapshot: string | null) => {
  if (reconcilingProjects && currentProject !== null && currentProject.isOwner) {
    projectGoneWhileReconciling = { snapshot };
    return;
  }
  window.setTimeout(() => void handleProjectGone(snapshot), 0);
};

// The server no longer has the project for this account. The owner's was
// deleted from another computer: the arrangement here is saved again as a
// new project rather than lost — it can be deleted again. A member's was
// closed to them (taken off it by the owner, or the owner deleted it): it
// is not theirs to keep, so this computer lets it go and opens another.
const handleProjectGone = async (serialized: string | null) => {
  if (currentProject === null) return;
  const { name, isOwner, id } = currentProject;
  currentProject = null;
  clearPendingEdits();
  writeCurrentProjectRecord();
  if (!isOwner) {
    lazyCreateSuppressed = true;
    showAlertDialog({
      title: t("projects.accessEndedTitle"),
      description: t("projects.accessEndedDescription", { name: nameForDialog(name) }),
    });
    // The list as the server has it now (on a load it is not in yet), so
    // that one of this account's own projects opens rather than a new one.
    projectList = projectList.filter((project) => project.id !== id);
    await refreshProjectList();
    await openNextProjectOrStartNew();
    return;
  }
  if (serialized === null || isArrangementEmpty()) return;
  const created = await ensureProjectForSnapshot(serialized, name);
  if (created.outcome !== "created") return;
  showAlertDialog({ title: t("projects.goneTitle"), description: t("projects.goneDescription") });
};

// --- The open project's name in the header ---

// While a project is open its name stands where the site name does
// (#projectNameInput for #logoTitle, index.php), and the tab is titled
// after it. The field is edited in place: Enter or leaving it renames,
// Escape puts the name back, and an empty field keeps the old name
// (renameProject). A name arriving from elsewhere — another member's
// rename, through the poll — is not written over typing in progress.
const renderProjectNameHeader = () => {
  const input = document.getElementById("projectNameInput") as HTMLInputElement | null;
  const title = document.getElementById("logoTitle");
  if (!input || !title) return;
  const name = currentProject?.name ?? null;
  input.hidden = name === null;
  title.hidden = name !== null;
  document.title = name === null ? SITE.name : `${name} – ${SITE.name}`;
  if (name !== null && document.activeElement !== input) input.value = name;
};

const initProjectNameHeader = () => {
  const input = document.getElementById("projectNameInput") as HTMLInputElement | null;
  if (!input) return;
  let escaped = false;
  input.addEventListener("keydown", (event) => {
    if (event.key === "Enter") input.blur();
    if (event.key === "Escape") {
      escaped = true;
      input.blur();
    }
  });
  input.addEventListener("blur", () => {
    const project = currentProject;
    if (project === null) return;
    const name = input.value.trim();
    if (escaped || name === "" || name === project.name) {
      escaped = false;
      input.value = project.name;
      return;
    }
    // The header shows what the rename came to: the server's spelling of
    // the name, or the old one when it was refused.
    void renameProject(project.id, name).then(renderProjectNameHeader);
  });
};

// --- Lining the copies up: on load and after signing in ---

const reconcileProjects = async (justSignedIn: boolean): Promise<void> => {
  projectsNote = null;
  projectSyncPaused = true;
  reconcilingProjects = true;
  projectGoneWhileReconciling = null;
  let listFresh = false;
  try {
    const record = readCurrentProjectRecord();
    if (record !== null && record.owner !== accountOwner()) {
      // Someone else's project, left here when their session ended. Not
      // this person's to continue, nor to save into their account: this
      // computer starts over for them (and reloads, so nothing below runs).
      currentProject = null;
      clearAllPendingEdits();
      writeCurrentProjectRecord();
      resetLocalArrangementAndReload();
      return;
    }
    currentProject = record;
    // (Shown now: offline, the lining up below writes nothing.)
    renderProjectNameHeader();
    // A record of a project the server no longer has (deleted elsewhere,
    // or a database since emptied) is let go here, and the plan on screen
    // goes the way of one with no record: saved as a new project, under
    // the old name, before the list is shown — a welcome at sign-in, the
    // word about the removal on a plain load.
    let goneName: string | null = null;
    if (currentProject !== null) {
      // The edits a closed tab left, and everything appended elsewhere
      // since this computer last looked (or the whole thing, for a record
      // from before the log).
      startSyncingProject();
      await syncNow({ evenIfPaused: true });
      if (projectGoneWhileReconciling !== null) {
        projectGoneWhileReconciling = null;
        goneName = currentProject.name;
        currentProject = null;
        clearPendingEdits();
        writeCurrentProjectRecord();
        renderProjectNameHeader();
      }
    }
    if (currentProject !== null) {
      // Lined up above.
    } else if (!isArrangementEmpty()) {
      const serialized = currentStoredSnapshot();
      if (serialized !== null) {
        const created = await ensureProjectForSnapshot(
          serialized,
          goneName ?? defaultProjectName(),
        );
        // (Refused — signed in on a full account, or with a plan too
        // large — it stays in this browser and waits, as the status says.)
        if (created.outcome === "created" && justSignedIn) {
          projectsNote = t("projects.savedOnSignIn", { name: created.project.name });
        } else if (created.outcome === "created" && goneName !== null) {
          showAlertDialog({
            title: t("projects.goneTitle"),
            description: t("projects.goneDescription"),
          });
        }
      }
    } else {
      await refreshProjectList();
      listFresh = true;
      if (projectList.length > 0) await openProject(projectList[0].id);
    }
    if (!listFresh) await refreshProjectList();
    // An invite link opened before (or just now): the project joins the
    // list and opens.
    await completePendingJoin();
    renderProjectsPanel();
  } finally {
    projectSyncPaused = false;
    reconcilingProjects = false;
    // Edits made meanwhile go now — unless the account is full, which an
    // edit does not change.
    if (hasPendingEdits() && getAccountUser() !== null && projectSyncStatus !== "limitReached") {
      void syncNow();
    }
  }
};

// The copies lined up again on request (share.ts, after a refused
// publish): a round with the server, the saved state laid down.
const reconcileCurrentProject = (): Promise<void> => syncNow({ checkpoint: true });

// The publish state as the server has it (another computer may have
// published or unpublished): everything but the revision and the sync
// bookkeeping, which stay this browser's.
const takePublishStateFrom = (summary: ProjectSummary) => {
  if (currentProject === null) return;
  currentProject.name = summary.name;
  currentProject.ownerFreeAccess = summary.ownerFreeAccess;
  currentProject.memberCount = summary.memberCount;
  currentProject.publishedAt = summary.publishedAt;
  currentProject.publishedRevision = summary.publishedRevision;
  currentProject.publishedRoomIds = summary.publishedRoomIds;
  currentProject.guestUrl = summary.guestUrl;
  currentProject.publishedUntil = summary.publishedUntil;
  currentProject.updatedAt = summary.updatedAt;
};

// A fresh summary of the current project from the server (after a publish
// or unpublish, share.ts).
const applySummaryToCurrentProject = (summary: ProjectSummary) => {
  if (currentProject !== null && currentProject.id === summary.id) {
    takePublishStateFrom(summary);
    currentProject.revision = summary.revision;
    currentProject.stateSeq = summary.stateSeq;
    writeCurrentProjectRecord();
  }
  const index = projectList.findIndex((project) => project.id === summary.id);
  if (index !== -1) projectList[index] = summary;
  renderProjectsPanel();
};

// The current project's summary fetched again (after a payment for its
// guests' page landed, share.ts): the publish state and the paid window as
// the server has them now. Null when it could not be had.
const refreshCurrentProjectSummary = async (): Promise<ProjectSummary | null> => {
  if (currentProject === null) return null;
  const { status, data } = await projectApi(
    `?id=${encodeURIComponent(currentProject.id)}&summary=1`,
  );
  if (status !== 200 || data === null) return null;
  const summary = readProjectSummary(data.project);
  if (summary !== null) applySummaryToCurrentProject(summary);
  return summary;
};

// --- The project list ---

const refreshProjectList = async () => {
  const { status, data } = await projectApi("");
  if (status !== 200 || data === null || !Array.isArray(data.projects)) return;
  projectList = data.projects
    .map(readProjectSummary)
    .filter((project): project is ProjectSummary => project !== null);
  renderProjectsPanel();
  retrySaveIfRoomFreed();
};

const openProject = async (id: string): Promise<boolean> => {
  if (currentProject?.id === id) return true;
  clearProjectsNote();
  await flushProjectSave();
  if (await openProjectFromServer(id)) return true;
  showAlertDialog({ title: t("projects.loadFailed"), description: "" });
  return false;
};

// An empty project in the account, opened. The current one stays.
const startNewProject = async () => {
  clearProjectsNote();
  await flushProjectSave();
  const roomId = mintId<RoomId>("room");
  const state = readPersistedSnapshot({
    version: PERSISTED_STATE_VERSION,
    allRooms: { [roomId]: {} },
  });
  if (!state) return;
  const serialized = JSON.stringify(state);
  const created = await createProject(serialized, datedProjectName());
  if (created.outcome === "refused") {
    showProjectRefusalDialog(created.reason);
    return;
  }
  if (created.outcome === "failed") {
    showAlertDialog({ title: t("projects.actionFailed"), description: "" });
    return;
  }
  if (adoptServerState(created.project, state)) await refreshProjectList();
};

const renameProject = async (id: string, name: string) => {
  const trimmed = name.trim();
  renamingProjectId = null;
  if (trimmed === "") {
    renderProjectsPanel();
    return;
  }
  const { status, data } = await projectApi("", { action: "rename", id, name: trimmed });
  const renamed = status === 200 && data !== null ? readProjectSummary(data.project) : null;
  if (renamed === null) {
    showAlertDialog({ title: t("projects.actionFailed"), description: "" });
    renderProjectsPanel();
    return;
  }
  const listed = projectList.find((project) => project.id === id);
  if (listed) listed.name = renamed.name;
  if (currentProject?.id === id) {
    currentProject.name = renamed.name;
    writeCurrentProjectRecord();
  }
  renderProjectsPanel();
};

const duplicateProject = async (id: string) => {
  await flushProjectSave();
  const source = projectList.find((project) => project.id === id);
  const { status, data } = await projectApi("", {
    action: "duplicate",
    id,
    name: t("projects.copyName", { name: source?.name ?? "" }),
  });
  const refusal = readProjectRefusal(status, data);
  if (refusal !== null) {
    showProjectRefusalDialog(refusal);
    return;
  }
  if (status !== 200) {
    showAlertDialog({ title: t("projects.actionFailed"), description: "" });
    return;
  }
  await refreshProjectList();
};

// Deleting the open project opens the newest other one, or a fresh one.
const confirmDeleteProject = (id: string) => {
  const project = projectList.find((candidate) => candidate.id === id);
  showConfirmDialog({
    title: t("projects.deleteTitle"),
    description:
      t("projects.deleteDescription", { name: nameForDialog(project?.name ?? "") }) +
      (project && project.memberCount > 0
        ? " " + tCount("projects.deleteSharedWarning", project.memberCount)
        : "") +
      (project?.published ? " " + t("projects.deletePublishedWarning") : ""),
    affirmativeLabel: t("projects.deleteConfirm"),
    onAffirmative: () => void deleteProject(id),
    dismissLabel: t("dialog.cancel"),
  });
};

const deleteProject = (id: string) => removeProjectFromAccount(id, "delete");

// Deleting (the owner) and leaving (a member) are the same from this
// account's side: the project goes from the list, and when it was the one
// open, the newest other one opens in its place.
const removeProjectFromAccount = async (id: string, action: "delete" | "leave") => {
  const wasCurrent = currentProject?.id === id;
  if (wasCurrent) {
    // No more edits into it; a request already out is left to finish.
    await waitForSyncIdle();
  }
  const { status } = await projectApi("", { action, id });
  if (status !== 200 && status !== 404) {
    // Still the current project, still saved into, as if nothing happened.
    showAlertDialog({ title: t("projects.actionFailed"), description: "" });
    return;
  }
  if (wasCurrent) {
    // Detached only now that it is gone — and the arrangement still on
    // screen is not to come back as a new project before the next one
    // opens.
    clearPendingEdits();
    currentProject = null;
    lazyCreateSuppressed = true;
    writeCurrentProjectRecord();
  }
  projectList = projectList.filter((project) => project.id !== id);
  renderProjectsPanel();
  // Only a deletion frees room in the account (a member's project counts
  // against its owner).
  if (action === "delete") retrySaveIfRoomFreed();
  if (wasCurrent) await openNextProjectOrStartNew();
};

// With no project open any more: the newest in the list, or a new one.
const openNextProjectOrStartNew = async () => {
  if (projectList.length > 0) await openProject(projectList[0].id);
  else await startNewProject();
};

// A query parameter that asks the app to do something once on arrival
// (?join=<id>, ?account): its value (the empty string for a bare name), and
// the parameter is taken off the address bar so a reload does not do it
// twice and a bookmark is clean. null when it is not there.
const takeQueryParam = (name: string): string | null => {
  const params = new URLSearchParams(window.location.search);
  const value = params.get(name);
  if (value === null) return null;
  params.delete(name);
  const query = params.toString();
  window.history.replaceState(null, "", window.location.pathname + (query ? `?${query}` : ""));
  return value;
};

// --- Joining a shared project through its invite link ---

// /app/?join=<id> on load: the id is parked for the sign-in to finish
// (reconcileProjects runs after it either way).
const readPendingJoinFromUrl = () => {
  const inviteId = takeQueryParam("join");
  if (inviteId === null) return;
  if (!isSafeId(inviteId)) return;
  try {
    sessionStorage.setItem(PENDING_JOIN_STORAGE_KEY, inviteId);
  } catch {
    // No session storage: the link is lost; opening it again does the same.
  }
};

const readPendingJoin = (): string | null => {
  try {
    return sessionStorage.getItem(PENDING_JOIN_STORAGE_KEY);
  } catch {
    return null;
  }
};

const clearPendingJoin = () => {
  try {
    sessionStorage.removeItem(PENDING_JOIN_STORAGE_KEY);
  } catch {
    // Nothing to clear.
  }
};

// account.ts shows the sign-in dialog with a word about it when someone
// arrives through a link signed out.
const hasPendingJoin = (): boolean => readPendingJoin() !== null;

// Signed in with a link waiting: the server makes this account a member and
// the project opens, a dialog says so (once, now — in the list it would be
// read after the project was already seen) — or that this account was in
// already, or is the owner's. A link that was removed (or never was) is
// said the same way and forgotten; a server that could not be reached
// keeps the link for the next load.
const completePendingJoin = async () => {
  const inviteId = readPendingJoin();
  if (inviteId === null || getAccountUser() === null) return;
  const { status, data } = await projectApi("", { action: "join", inviteId });
  if (status === 404) {
    clearPendingJoin();
    showAlertDialog({
      title: t("projects.joinInvalidTitle"),
      description: t("projects.joinInvalid"),
    });
    return;
  }
  if (status !== 200 || data === null) return;
  const joined = readProjectSummary(data.project);
  if (joined === null) return;
  clearPendingJoin();
  await refreshProjectList();
  if (currentProject?.id !== joined.id) {
    // Opened here rather than through openProject, the reconcile having the
    // sync paused — but the edits of the project open until now go first,
    // as openProject would have it. The pause is lifted for that: nothing
    // else is in flight at this point.
    if (currentProject !== null && hasPendingEdits()) {
      projectSyncPaused = false;
      await flushProjectSave();
      projectSyncPaused = true;
    }
    await openProjectFromServer(joined.id);
  }
  const name = nameForDialog(joined.name);
  if (data.membership === "owner") {
    showAlertDialog({
      title: t("projects.ownInviteTitle"),
      description: t("projects.ownInvite", { name }),
    });
  } else if (data.membership === "member") {
    showAlertDialog({
      title: t("projects.alreadyMemberTitle"),
      description: t("projects.alreadyMember", { name }),
    });
  } else {
    showAlertDialog({
      title: t("projects.joinedTitle"),
      description: t("projects.joined", { name, owner: nameForDialog(ownerLabel(joined)) }),
    });
  }
};

// --- Members: the owner's view of who shares the project ---

type ProjectMember = { memberId: number; name: string; email: string; addedAt: number };
type ProjectMembersAnswer = { members: ProjectMember[]; inviteUrl: string | null };

// The project whose members view is open (account.ts shows the view), and
// the server's last answer about it.
let membersProjectId: string | null = null;
let membersAnswer: ProjectMembersAnswer | null = null;
let membersError: string | null = null;
const INVITE_LINK_COPIED_MS = 2000;

const readMembersAnswer = (data: RawSnapshot | null): ProjectMembersAnswer | null => {
  if (data === null || !Array.isArray(data.members)) return null;
  const members: ProjectMember[] = [];
  for (const entry of data.members) {
    if (!isPlainRecord(entry) || typeof entry.memberId !== "number") continue;
    members.push({
      memberId: entry.memberId,
      name: typeof entry.name === "string" ? entry.name : "",
      email: typeof entry.email === "string" ? entry.email : "",
      addedAt: typeof entry.addedAt === "number" ? entry.addedAt : 0,
    });
  }
  return { members, inviteUrl: typeof data.inviteUrl === "string" ? data.inviteUrl : null };
};

// The "share with others" action on an owned project's row.
const openMembersView = (id: string) => {
  membersProjectId = id;
  membersAnswer = null;
  membersError = null;
  showAccountDialogView("members");
  void membersRequest({ action: "members", id });
};

// One of the members actions; the answer (members + link) replaces what
// is shown. False when it failed, with the error line set.
const membersRequest = async (body: object): Promise<boolean> => {
  if (membersProjectId === null) return false;
  const { status, data } = await projectApi("", body);
  if (status === 200) {
    const answer = readMembersAnswer(data);
    if (answer !== null) {
      membersAnswer = answer;
      membersError = null;
      renderMembersView();
      return true;
    }
  }
  if (status === 404 || status === 403) {
    // Gone, or not this account's to manage any more: back to the list.
    membersProjectId = null;
    await refreshProjectList();
    showAccountDialogView("account");
    return false;
  }
  membersError = t("projects.actionFailed");
  renderMembersView();
  return false;
};

const createInviteLink = async (renew: boolean) => {
  if (membersProjectId === null) return;
  const { status, data } = await projectApi("", {
    action: "inviteLink",
    id: membersProjectId,
    renew,
  });
  if (status === 200 && data !== null && typeof data.inviteUrl === "string") {
    if (membersAnswer === null) membersAnswer = { members: [], inviteUrl: null };
    membersAnswer.inviteUrl = data.inviteUrl;
    membersError = null;
  } else {
    membersError = t("projects.actionFailed");
  }
  renderMembersView();
};

const revokeInviteLink = async () => {
  if (membersProjectId === null) return;
  const { status } = await projectApi("", { action: "revokeInviteLink", id: membersProjectId });
  if (status === 200) {
    if (membersAnswer !== null) membersAnswer.inviteUrl = null;
    membersError = null;
  } else {
    membersError = t("projects.actionFailed");
  }
  renderMembersView();
};

const copyInviteLink = async () => {
  const url = membersAnswer?.inviteUrl;
  const input = document.getElementById("membersInviteLink") as HTMLInputElement | null;
  if (!url || !input) return;
  try {
    await navigator.clipboard.writeText(url);
  } catch {
    // No clipboard permission (or no secure context): select the text so
    // the person can copy it themselves.
    input.focus();
    input.select();
    return;
  }
  const label = $("#membersCopyButton");
  label.text(t("projects.linkCopied"));
  window.setTimeout(() => label.text(t("projects.copyLink")), INVITE_LINK_COPIED_MS);
};

const removeMember = (memberId: number) => {
  if (membersProjectId === null) return;
  void membersRequest({ action: "removeMember", id: membersProjectId, memberId });
};

const renderMembersView = () => {
  const view = document.getElementById("accountMembers");
  if (!view || membersProjectId === null) return;
  const project = projectList.find((candidate) => candidate.id === membersProjectId);
  $("#membersProjectName").text(project?.name ?? "");
  const error = document.getElementById("accountMembersError");
  if (error) {
    error.textContent = membersError ?? "";
    error.hidden = membersError === null;
  }
  const loaded = membersAnswer !== null;
  const inviteUrl = membersAnswer?.inviteUrl ?? null;
  $("#membersLinkRow").prop("hidden", !loaded || inviteUrl === null);
  $("#membersCreateLinkButton").prop("hidden", !loaded || inviteUrl !== null);
  $("#membersInviteLink").val(inviteUrl ?? "");
  const list = document.getElementById("membersList");
  if (!list) return;
  list.replaceChildren();
  if (!loaded) return;
  if (membersAnswer!.members.length === 0) {
    list.appendChild(projectElement("p", "membersEmpty faintText", t("projects.noMembers")));
    return;
  }
  for (const member of membersAnswer!.members) {
    const row = projectElement("div", "memberRow");
    const who = projectElement("div", "memberWho");
    who.appendChild(projectElement("span", "memberName", member.name || member.email));
    if (member.name) who.appendChild(projectElement("span", "memberEmail", member.email));
    row.appendChild(who);
    const remove = projectElement("button", "memberRemove", t("projects.removeMember"));
    remove.type = "button";
    remove.addEventListener("click", () => removeMember(member.memberId));
    row.appendChild(remove);
    list.appendChild(row);
  }
};

// --- Leaving a project shared with this account ---

const confirmLeaveProject = (id: string) => {
  const project = projectList.find((candidate) => candidate.id === id);
  showConfirmDialog({
    title: t("projects.leaveTitle"),
    description: t("projects.leaveDescription", {
      name: nameForDialog(project?.name ?? ""),
      owner: nameForDialog(project ? ownerLabel(project) : ""),
    }),
    affirmativeLabel: t("projects.leaveConfirm"),
    onAffirmative: () => void leaveProject(id),
    dismissLabel: t("dialog.cancel"),
  });
};

// As deleting, from this account's side: the project goes from the list
// (it stays the owner's), and the newest other one opens if it was open.
const leaveProject = async (id: string) => {
  const wasCurrent = currentProject?.id === id;
  if (wasCurrent) await waitForSyncIdle();
  const { status } = await projectApi("", { action: "leave", id });
  if (status !== 200 && status !== 404) {
    showAlertDialog({ title: t("projects.actionFailed"), description: "" });
    return;
  }
  if (wasCurrent) {
    clearPendingEdits();
    currentProject = null;
    lazyCreateSuppressed = true;
    writeCurrentProjectRecord();
  }
  projectList = projectList.filter((project) => project.id !== id);
  renderProjectsPanel();
  if (!wasCurrent) return;
  if (projectList.length > 0) await openProject(projectList[0].id);
  else await startNewProject();
};

// --- Rendering, inside the account dialog's signed-in side ---

const formatProjectTime = (epochSeconds: number): string =>
  new Date(epochSeconds * 1000).toLocaleString(appLocale(), {
    year: "numeric",
    month: "short",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });

// The account's word in the room's corner (#syncPill): only when there is
// one. A refusal or a failed save stays until a save lands; a version from
// another computer just taken in is said for a few seconds, so that the
// plan changing under one's hands is explained, then goes. Saving, and
// saved, are not news.
const renderProjectsStatus = () => {
  // The share panel's "changes the guests don't see yet" follows the same
  // state.
  renderShareSection();
  const pill = document.getElementById("syncPill");
  if (!pill) return;
  window.clearTimeout(syncNoticeTimer);
  let text = projectRefusalText();
  let error = text !== null;
  if (text === null) {
    const noticeLeft = SYNC_NOTICE_MS - (Date.now() - syncNoticeShownAt);
    if ((projectSyncStatus === "merged" || projectSyncStatus === "updated") && noticeLeft > 0) {
      if (projectSyncStatus === "merged") {
        text = t("projects.statusMerged");
        if (lastMergeOverridden > 0) {
          text += " " + tCount("projects.statusOverridden", lastMergeOverridden);
        }
      } else {
        text = t("projects.statusUpdated");
      }
      syncNoticeTimer = window.setTimeout(renderProjectsStatus, noticeLeft);
    } else if (projectSyncStatus === "failed") {
      text = t("projects.statusFailed");
      error = true;
    }
  }
  pill.textContent = text ?? "";
  pill.hidden = text === null;
  pill.classList.toggle("syncPillError", error);
};

const projectElement = <K extends keyof HTMLElementTagNameMap>(
  tag: K,
  className: string,
  text?: string,
): HTMLElementTagNameMap[K] => {
  const element = document.createElement(tag);
  element.className = className;
  if (text !== undefined) element.textContent = text;
  return element;
};

// The PDF download credits left on the account's purchase, above the list
// (one purchase serves every project, so not per row). Shown only while
// there are some: nothing bought, all spent, a free account or an
// unanswered check all leave the line out. The paywall re-renders it as
// its state changes (paywall.ts).
const renderProjectsPdfDownloads = () => {
  const line = document.getElementById("projectsPdfDownloads");
  if (!line) return;
  const downloadsLeft = getPdfDownloadsLeft();
  const show = downloadsLeft !== undefined && downloadsLeft > 0;
  line.hidden = !show;
  line.textContent = show ? tCount("projects.pdfDownloadsLeft", downloadsLeft) : "";
};

const renderProjectsPanel = () => {
  renderShareSection();
  const list = document.getElementById("projectsList");
  if (!list) return;
  const note = document.getElementById("projectsNote");
  if (note) {
    note.textContent = projectsNote ?? "";
    note.hidden = projectsNote === null;
  }
  renderProjectsPdfDownloads();
  renderProjectsStatus();

  list.replaceChildren();
  if (projectList.length === 0) {
    list.appendChild(projectElement("p", "projectsEmpty faintText", t("projects.empty")));
    return;
  }
  // This account's own first; the ones shared with it under a heading of
  // their own, so a project someone invited this person to is easy to find.
  const own = projectList.filter((project) => project.isOwner);
  const shared = projectList.filter((project) => !project.isOwner);
  if (shared.length > 0 && own.length > 0) {
    list.appendChild(projectElement("h5", "projectsGroupTitle", t("projects.yourProjects")));
  }
  for (const project of own) list.appendChild(renderProjectRow(project));
  if (shared.length > 0) {
    list.appendChild(projectElement("h5", "projectsGroupTitle", t("projects.sharedWithYou")));
    for (const project of shared) list.appendChild(renderProjectRow(project));
  }
};

const renderProjectRow = (project: ProjectSummary): HTMLElement => {
  const isCurrent = project.id === currentProject?.id;
  const row = projectElement("div", "projectRow" + (isCurrent ? " currentProject" : ""));
  row.dataset.projectId = project.id;

  if (renamingProjectId === project.id) {
    const input = projectElement("input", "projectRenameInput");
    input.type = "text";
    input.value = project.name;
    input.maxLength = 100;
    let done = false;
    const finish = () => {
      if (done) return;
      done = true;
      void renameProject(project.id, input.value);
    };
    input.addEventListener("keydown", (event) => {
      if (event.key === "Enter") finish();
      if (event.key === "Escape") {
        done = true;
        renamingProjectId = null;
        renderProjectsPanel();
      }
    });
    input.addEventListener("blur", finish);
    row.appendChild(input);
    window.setTimeout(() => {
      input.focus();
      input.select();
    }, 0);
    return row;
  }

  const open = projectElement("button", "projectOpen");
  open.type = "button";
  open.appendChild(projectElement("span", "projectName", project.name));
  // The badges on a line of their own under the name, so a long name
  // (cut off with an ellipsis) never hides them.
  const sharedWith = project.isOwner && project.memberCount > 0;
  if (isCurrent || project.published || sharedWith) {
    const badges = projectElement("span", "projectBadges");
    if (isCurrent) {
      badges.appendChild(projectElement("span", "projectCurrentBadge", t("projects.current")));
    }
    if (project.published) {
      badges.appendChild(projectElement("span", "projectPublishedBadge", t("projects.published")));
    }
    if (sharedWith) {
      badges.appendChild(
        projectElement(
          "span",
          "projectSharedBadge",
          tCount("projects.sharedWith", project.memberCount),
        ),
      );
    }
    open.appendChild(badges);
  }
  open.appendChild(
    projectElement(
      "span",
      "projectMeta",
      [
        tCount("projects.rooms", project.roomCount),
        tCount("projects.guests", project.guestCount),
        tCount("projects.tables", project.tableCount),
      ].join(" · "),
    ),
  );
  open.appendChild(
    projectElement(
      "span",
      "projectMeta",
      t("projects.edited", { time: formatProjectTime(project.updatedAt) }),
    ),
  );
  if (!project.isOwner) {
    open.appendChild(
      projectElement("span", "projectMeta", t("projects.sharedBy", { name: ownerLabel(project) })),
    );
  }
  open.addEventListener("click", () => {
    void openProject(project.id).then((opened) => {
      if (opened) closeAccountDialog();
    });
  });
  row.appendChild(open);

  const actions = projectElement("div", "projectActions");
  const action = (label: string, onClick: () => void) => {
    const button = projectElement("button", "", label);
    button.type = "button";
    button.addEventListener("click", onClick);
    actions.appendChild(button);
  };
  action(t("projects.rename"), () => {
    renamingProjectId = project.id;
    renderProjectsPanel();
  });
  action(t("projects.duplicate"), () => void duplicateProject(project.id));
  if (project.isOwner) {
    action(t("projects.share"), () => openMembersView(project.id));
    action(t("projects.delete"), () => confirmDeleteProject(project.id));
  } else {
    action(t("projects.leave"), () => confirmLeaveProject(project.id));
  }
  row.appendChild(actions);
  return row;
};

// Signing out (account.ts, after the pending save went out): the project
// stays in the account; this computer forgets it and starts pristine.
const onAccountSignedOut = () => {
  clearAllPendingEdits();
  currentProject = null;
  writeCurrentProjectRecord();
  resetLocalArrangementAndReload();
};

// Deleting the account (account.ts): nothing may reach the server while
// that request is out. A save or creation landing after the rows are gone
// is refused where the foreign keys hold, and where they don't it would
// leave a project nobody owns, with the guest names the deletion promised
// to remove. Paused the way reconcileProjects pauses, after waiting for
// what is already out; resumeProjectSync undoes it when the deletion was
// refused (edits made meanwhile then go).
const suspendProjectSync = async () => {
  projectSyncPaused = true;
  await waitForSyncIdle();
  if (projectCreation) await projectCreation.catch(() => null);
};

const resumeProjectSync = () => {
  projectSyncPaused = false;
  // Edits made meanwhile go, at the ordinary pace.
  if (getAccountUser() !== null) scheduleSync(SYNC_SEND_DELAY_MS);
};

// Called from the startup block in index.php, before initAccount (whose
// reconcile needs the listener in place).
const initProjects = () => {
  readPendingJoinFromUrl();
  initProjectNameHeader();
  initSync();
};
