// The open project kept in step with the account's copy and with the other
// people in it (api/project-sync.php). Every edit made here (history.ts
// hands them on: an action's operations, or what an undo came to) is
// appended to the project's log on the server, and every edit appended
// there by someone else is fetched and applied here — the same request
// does both. The server's order of the log is the one truth: edits from
// it apply without undo's guard (the last set wins), and this computer's
// own edits that the server has not placed yet are applied again on top,
// since they will come after in the log. So every copy comes out alike.
//
// A request goes out shortly after an edit, and otherwise as a poll — every
// few seconds while the project is shared, less often alone. Now and then,
// when this computer has nothing of its own in flight, it lays down a
// CHECKPOINT: the whole state as of the log's head, which is what the
// server keeps as the project's saved state (publishing, the list's counts,
// a newly opened project). Edits not yet accepted are kept in localStorage,
// so a tab closed early sends them on the next load (the server takes an
// edit once, by its id).
//
// A client that fell too far behind (the log compacted past it, or a record
// from before the log) gets the checkpoint and the edits since: that
// version is merged with what is on screen (merge.ts) and the difference
// sent as one edit. Nothing here runs for anonymous sessions.

const SYNC_ENDPOINT = "/api/project-sync.php";
// This tab's name in the log: tells its own edits apart in what it fetches.
const SYNC_CLIENT_ID_STORAGE_KEY = "seatingApp.clientId";
// The edits the server has not yet taken, with the project they belong to.
const SYNC_PENDING_STORAGE_KEY = "seatingApp.pendingEdits";
// An edit goes out this soon after it was made (several in a row go
// together)…
const SYNC_SEND_DELAY_MS = 300;
// …and a request that got no answer (offline, server down) is tried again
// this often.
const SYNC_RETRY_MS = 30000;
// How often a visible tab asks for others' edits: with other members in the
// project, often enough to feel live; alone, rarely (another computer of
// one's own, or a publish made there).
const SYNC_POLL_SHARED_MS = 3000;
const SYNC_POLL_ALONE_MS = 8000;
// While two tabs are being introduced (presence.ts): their signals travel
// with the rounds, so the rounds come quicker for the moment.
const SYNC_POLL_SIGNALLING_MS = 1000;
// A drag in progress has the DOM ahead of the data; a request waits this
// long and looks again.
const SYNC_DRAG_WAIT_MS = 400;
// A checkpoint follows the last edit this long after, once nothing is out.
const SYNC_CHECKPOINT_DELAY_MS = 3000;
// The look for changes made outside the protocol (history.ts) serialises
// the whole arrangement; a round with nothing to send does it this often
// at most, so an idle poll costs nothing.
const SYNC_SWEEP_EVERY_MS = 10000;
// api/project-sync.php's SYNC_MAX_EDITS.
const SYNC_MAX_EDITS_PER_REQUEST = 200;
// How much of edits one request carries (their JSON), and the size above
// which one edit is split into several (a merge's difference, a big guest
// import) — well under the server's cap per edit, and together with a
// checkpoint of the largest state still under PHP's default post size.
const SYNC_MAX_REQUEST_EDIT_BYTES = 900_000;
const SYNC_SPLIT_EDIT_BYTES = 400_000;
// fetch's keepalive budget on leaving the page.
const SYNC_KEEPALIVE_MAX_BYTES = 60000;

// `group`: the parts of one edit split for size travel in one request (see
// splitEdit), so every copy applies them together.
type SyncEdit = { id: string; ops: EditOp[]; group?: string };
type SyncIncomingEdit = { seq: number; opId: string; clientId: string; ops: EditOp[] };

let pendingEdits: SyncEdit[] = [];
// The edits of the request out right now (a subset of pendingEdits), so
// an edit made meanwhile is told apart from one the answer accepts.
let syncInFlight: Promise<void> | null = null;
let syncSendTimer: number | undefined;
let syncPollTimer: number | undefined;
let syncCheckpointTimer: number | undefined;
// Whether the next request should lay the state down as a checkpoint.
let syncCheckpointWanted = false;
// Set when others' edits could not be shown here: the next round asks for
// the server's version in whole instead of the edits since.
let syncResyncWanted = false;
// While a round closes the open edit and sweeps (syncRound), the edits that
// come of it are for this very request, not for a send of their own.
let syncCollecting = false;
let lastSweepAt = 0;
const editBytesCache = new WeakMap<SyncEdit, number>();
let syncClientIdInMemory: string | null = null;
// The export settings as last sent or taken in: they are part of the
// project (the names setting is published with it) but not of undo, so
// history.ts does not hand their changes on; this file looks for them.
let lastKnownExportSettings: string | null = null;
const EXPORT_SETTINGS_RULES: EditRules = { ignoredKeys: new Set(), defaults: {} };

const syncClientId = (): string => {
  if (syncClientIdInMemory !== null) return syncClientIdInMemory;
  let id: string | null = null;
  try {
    id = window.sessionStorage.getItem(SYNC_CLIENT_ID_STORAGE_KEY);
    if (id === null) {
      id = mintId("client");
      window.sessionStorage.setItem(SYNC_CLIENT_ID_STORAGE_KEY, id);
    }
  } catch {
    id = id ?? mintId("client");
  }
  syncClientIdInMemory = id;
  return id;
};

// --- Pending edits, kept in localStorage until accepted ---

// The store holds every tab's pending edits per project under its client
// id, so one tab's round never wipes another's, and a project left with
// edits unsent keeps them until it is opened here again:
// {"clientId:projectId": {projectId, edits}}.
type SyncPendingStore = { [key: string]: { projectId: string; edits: SyncEdit[] } };

const readPendingStore = (): SyncPendingStore => {
  const raw = readStoredString(SYNC_PENDING_STORAGE_KEY);
  if (raw === null) return {};
  try {
    const value: unknown = JSON.parse(raw);
    return isPlainRecord(value) ? (value as SyncPendingStore) : {};
  } catch {
    return {};
  }
};

const writePendingStore = (store: SyncPendingStore) => {
  if (Object.keys(store).length === 0) removeStoredString(SYNC_PENDING_STORAGE_KEY);
  else writeStoredString(SYNC_PENDING_STORAGE_KEY, JSON.stringify(store));
};

const pendingStoreKey = (projectId: string): string => syncClientId() + ":" + projectId;

const writePendingEdits = () => {
  if (currentProject === null) return;
  const store = readPendingStore();
  const key = pendingStoreKey(currentProject.id);
  if (pendingEdits.length === 0) delete store[key];
  else store[key] = { projectId: currentProject.id, edits: pendingEdits };
  writePendingStore(store);
};

const isStoredEdit = (edit: unknown): edit is SyncEdit =>
  isPlainRecord(edit) &&
  typeof edit.id === "string" &&
  Array.isArray(edit.ops) &&
  (edit.group === undefined || typeof edit.group === "string");

// The edits tabs left for this project — a tab closed early, this tab
// before it switched away, or a tab still open (its own copy stays with
// it; the server takes an edit once, so both sending is harmless). Taken
// over by this tab, which stores them under its own key at once.
const readPendingEdits = (projectId: string): SyncEdit[] => {
  const store = readPendingStore();
  const taken: SyncEdit[] = [];
  const seen = new Set<string>();
  for (const key of Object.keys(store)) {
    const entry = store[key];
    if (!isPlainRecord(entry) || entry.projectId !== projectId || !Array.isArray(entry.edits)) {
      continue;
    }
    for (const edit of entry.edits) {
      if (isStoredEdit(edit) && !seen.has(edit.id)) {
        seen.add(edit.id);
        taken.push(edit);
      }
    }
    delete store[key];
  }
  if (taken.length > 0) store[pendingStoreKey(projectId)] = { projectId, edits: taken };
  writePendingStore(store);
  return taken;
};

const stopPendingTimers = () => {
  window.clearTimeout(syncSendTimer);
  window.clearTimeout(syncCheckpointTimer);
  syncCheckpointWanted = false;
};

// Switching to another project: this one's unsent edits stay stored under
// it (sent when it is opened here again); this tab just lets go of them.
const detachPendingEdits = () => {
  writePendingEdits();
  pendingEdits = [];
  stopPendingTimers();
  leavePresence(true);
};

// The project is gone from this account (deleted, left, access ended): its
// edits have nowhere to go.
const clearPendingEdits = () => {
  pendingEdits = [];
  stopPendingTimers();
  leavePresence(false);
  if (currentProject !== null) {
    const store = readPendingStore();
    for (const key of Object.keys(store)) {
      if (store[key]?.projectId === currentProject.id) delete store[key];
    }
    writePendingStore(store);
  }
};

// Signing out, or another account's record found: nothing stored here is
// this account's to send.
const clearAllPendingEdits = () => {
  pendingEdits = [];
  stopPendingTimers();
  leavePresence(false);
  removeStoredString(SYNC_PENDING_STORAGE_KEY);
};

const hasPendingEdits = (): boolean => pendingEdits.length > 0;

// --- Edits made here ---

// history.ts's listener: every edit made on this computer. With a project
// open the edit is kept whatever the session's state — one that lapsed (a
// 401) comes back with the next sign-in, and the edits made meanwhile go
// then; without a project there is nothing to keep it under.
const onLocalEdit = (edit: CommittedEdit) => {
  // Taking in a server version is not an edit of ours (adoptServerState
  // applies it with nothing listening, but belt and braces).
  if (adoptingServerSnapshot) return;
  // An edit here is the end of the "updated from elsewhere" notice.
  if (projectSyncStatus === "updated" || projectSyncStatus === "merged") {
    projectSyncStatus = "saved";
  }
  if (currentProject === null) {
    // No project yet: the arrangement becomes one as a whole (a snapshot),
    // edits included — unless the account refused that and the plan waits.
    if (
      getAccountUser() !== null &&
      !projectSyncPaused &&
      !syncCollecting &&
      projectSyncStatus !== "limitReached"
    ) {
      scheduleSync(SYNC_SEND_DELAY_MS);
    }
    return;
  }
  pendingEdits.push(edit);
  writePendingEdits();
  if (getAccountUser() === null || projectSyncPaused || syncCollecting) return;
  scheduleSync(SYNC_SEND_DELAY_MS);
};

// --- Sizing a request ---

const editJsonBytes = (edit: SyncEdit): number => {
  let bytes = editBytesCache.get(edit);
  if (bytes === undefined) {
    bytes = new TextEncoder().encode(JSON.stringify({ opId: edit.id, ops: edit.ops })).length;
    editBytesCache.set(edit, bytes);
  }
  return bytes;
};

// An edit too big for one request's share goes as several parts, in order
// (its ops are independent of one another: each names its own path), all
// of one group: they are sent in one request and so applied together by
// everyone — a seat moved in one part and freed in another must not be
// judged apart (edits.ts, one guest per chair). One op alone is never over
// the cap in practice; it goes as it is.
const splitEdit = (edit: SyncEdit): SyncEdit[] => {
  if (edit.ops.length < 2 || editJsonBytes(edit) <= SYNC_SPLIT_EDIT_BYTES) return [edit];
  const group = mintId("group");
  const parts: SyncEdit[] = [];
  let ops: EditOp[] = [];
  let bytes = 0;
  for (const op of edit.ops) {
    const opBytes = new TextEncoder().encode(JSON.stringify(op)).length;
    if (ops.length > 0 && bytes + opBytes > SYNC_SPLIT_EDIT_BYTES) {
      parts.push({ id: mintId("edit"), ops, group });
      ops = [];
      bytes = 0;
    }
    ops.push(op);
    bytes += opBytes;
  }
  if (ops.length > 0) parts.push({ id: mintId("edit"), ops, group });
  return parts;
};

// The pending edits that go in the next request, and their size: big ones
// split first, then as many from the front as fit the request's share —
// a group of parts whole, whatever its size (the body still fits: no
// checkpoint rides along with an oversize set, see syncRound).
const packEditsForRequest = (): { edits: SyncEdit[]; bytes: number } => {
  if (pendingEdits.some((edit) => editJsonBytes(edit) > SYNC_SPLIT_EDIT_BYTES)) {
    pendingEdits = pendingEdits.flatMap(splitEdit);
    writePendingEdits();
  }
  const packed: SyncEdit[] = [];
  let bytes = 0;
  let index = 0;
  while (index < pendingEdits.length) {
    const edit = pendingEdits[index];
    const set =
      edit.group === undefined
        ? [edit]
        : pendingEdits.slice(index).filter((candidate) => candidate.group === edit.group);
    const setBytes = set.reduce((sum, part) => sum + editJsonBytes(part), 0);
    const full =
      bytes + setBytes > SYNC_MAX_REQUEST_EDIT_BYTES ||
      packed.length + set.length > SYNC_MAX_EDITS_PER_REQUEST;
    if (packed.length > 0 && full) break;
    packed.push(...set);
    bytes += setBytes;
    index += set.length;
  }
  return { edits: packed, bytes };
};

const scheduleSync = (delayMs: number) => {
  window.clearTimeout(syncSendTimer);
  syncSendTimer = window.setTimeout(() => void syncNow(), delayMs);
};

// The project's state becomes a project in the account (the first autosave
// after signing in, or the owner's deleted project saved again): what the
// snapshot had is on the server; what was edited since it was taken (while
// the request was out) goes on as an edit.
const afterProjectCreated = (serializedSent: string) => {
  markExportSettingsAsKnown();
  const sent = JSON.parse(serializedSent) as DataRecord;
  const live = JSON.parse(serializeHistorySnapshot()) as DataRecord;
  const ops = diffPersistedStates(
    liveUpdateStrip(sent, HISTORY_EDIT_RULES),
    live,
    HISTORY_EDIT_RULES,
  );
  if (ops.length > 0) {
    pendingEdits.push({ id: mintId("edit"), ops });
    writePendingEdits();
    scheduleSync(SYNC_SEND_DELAY_MS);
  }
};

// A change to the export settings since they were last accounted for
// becomes an edit (field by field), without touching undo.
const sweepExportSettings = () => {
  const now = JSON.stringify(exportSettings);
  if (lastKnownExportSettings === null) {
    lastKnownExportSettings = now;
    return;
  }
  if (now === lastKnownExportSettings) return;
  const ops = diffPersistedStates(
    { exportSettings: JSON.parse(lastKnownExportSettings) as DataRecord },
    { exportSettings: JSON.parse(now) as DataRecord },
    EXPORT_SETTINGS_RULES,
  );
  lastKnownExportSettings = now;
  if (ops.length === 0 || currentProject === null) return;
  pendingEdits.push({ id: mintId("edit"), ops });
  writePendingEdits();
};

const markExportSettingsAsKnown = () => {
  lastKnownExportSettings = JSON.stringify(exportSettings);
};

// Export settings arriving from elsewhere: applied to the settings
// themselves (the arrangement's read path leaves them out), the panel
// following.
const applyIncomingExportSettings = (ops: EditOp[]) => {
  if (ops.length === 0) return;
  const holder: DataRecord = { exportSettings: cloneData(exportSettings) };
  applyEditOps(holder, ops, EXPORT_SETTINGS_RULES, false);
  if (isDataRecord(holder.exportSettings)) {
    const settings = exportSettings as unknown as DataRecord;
    for (const key of Object.keys(settings)) {
      if (!(key in holder.exportSettings)) delete settings[key];
    }
    Object.assign(exportSettings, holder.exportSettings);
  }
  syncExportPanelFromSettings();
  markExportSettingsAsKnown();
};

const isExportSettingsOp = (op: EditOp): boolean => op.path[0] === "exportSettings";

// --- The request ---

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

const syncApi = async (body: object): Promise<SyncApiResult> => {
  try {
    const response = await fetch(SYNC_ENDPOINT, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    });
    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 };
  }
};

// The live state as the server stores it, for a checkpoint; null when a
// save is not possible right now.
const checkpointBody = (): { body: RawSnapshot; serialized: string } | null => {
  const serialized = currentStoredSnapshot();
  if (serialized === null || snapshotOverLimit(serialized)) return null;
  const state = parseSerializedSnapshot(serialized);
  return { body: { state, ...countsOf(state) }, serialized };
};

// One round with the server: this computer's pending edits out, others'
// edits in, a checkpoint when wanted and possible. One at a time; a second
// caller waits for the first and runs after it.
const syncNow = async (
  options: { checkpoint?: boolean; evenIfPaused?: boolean } = {},
): Promise<void> => {
  if (options.checkpoint) syncCheckpointWanted = true;
  if (syncInFlight) {
    // Every waiter, not only the first: a round started by one waiter is
    // waited for by the next.
    while (syncInFlight) await syncInFlight;
    // What those rounds left pending (an edit made meanwhile, a signal to
    // another tab) is the next caller's to send; a checkpoint still wanted
    // goes with it.
    if (
      !hasPendingEdits() &&
      !syncCheckpointWanted &&
      !syncResyncWanted &&
      !presenceSignalsWaiting()
    ) {
      return;
    }
  }
  syncInFlight = (async () => {
    try {
      await syncRound(options.evenIfPaused === true);
    } finally {
      syncInFlight = null;
    }
  })();
  await syncInFlight;
};

const syncRound = async (evenIfPaused: boolean) => {
  window.clearTimeout(syncSendTimer);
  if (getAccountUser() === null || (projectSyncPaused && !evenIfPaused)) return;
  // Mid-gesture the DOM is ahead of the data: no edit is sent or applied
  // under a drag; the request looks again shortly. Only the word that this
  // tab is still here goes out meanwhile (a long drag, or a gesture left
  // open by a pointer that left the window, must not make it vanish for
  // the others) — a round without edits, now and then.
  const dragging = isDragInProgress();
  if (dragging) {
    scheduleSync(SYNC_DRAG_WAIT_MS);
    if (currentProject === null || !presenceHeartbeatDue()) return;
  } else {
    // The edit in progress (typing, say) goes too — and a change made
    // outside the protocol becomes one (history.ts).
    // (The look for changes made outside the protocol serialises everything:
    // when there is something to send anyway, else now and then.)
    syncCollecting = true;
    try {
      commitEdit();
      if (
        hasPendingEdits() ||
        syncCheckpointWanted ||
        Date.now() - lastSweepAt > SYNC_SWEEP_EVERY_MS
      ) {
        sweepUnrecordedChanges();
        sweepExportSettings();
        lastSweepAt = Date.now();
      }
    } finally {
      syncCollecting = false;
    }
  }

  if (currentProject === null) {
    await createProjectFromArrangement();
    return;
  }
  const project = currentProject;
  const { edits, bytes: editBytes } = dragging ? { edits: [], bytes: 0 } : packEditsForRequest();
  const body: RawSnapshot = {
    id: project.id,
    clientId: syncClientId(),
    // Asking from nothing brings the server's version in whole.
    sinceSeq: syncResyncWanted ? null : project.syncedSeq,
    edits: edits.map((edit) => ({ opId: edit.id, ops: edit.ops })),
  };
  // This tab is here, looking at this room; the answer says who else is.
  // Not from a hidden tab (a checkpoint of its may still go): it left when
  // it was hidden, and its timers are throttled anyway.
  if (presenceAnnouncing()) {
    body.presence = { roomId: currentRoomId };
    presenceRequestSent();
  }
  const signals = takeOutgoingSignals();
  if (signals.length > 0) body.signals = signals;
  // A checkpoint is of a state that holds everything this computer has
  // applied plus the edits in this very request: nothing else may be
  // pending, and the server takes it only if nobody else appended since.
  // (And not beside an oversize set of edits: the body must stay under
  // PHP's post size.)
  const checkpointing =
    !dragging &&
    syncCheckpointWanted &&
    !syncResyncWanted &&
    project.syncedSeq !== null &&
    edits.length === pendingEdits.length &&
    editBytes <= SYNC_MAX_REQUEST_EDIT_BYTES;
  let checkpointSerialized: string | null = null;
  if (checkpointing) {
    const checkpoint = checkpointBody();
    if (checkpoint !== null) {
      body.checkpoint = { seq: project.syncedSeq, ...checkpoint.body };
      checkpointSerialized = checkpoint.serialized;
    } else if (currentStoredSnapshot() !== null) {
      // Known to be over the server's cap: said in the corner, the edits
      // still go.
      noteProjectSaveRefused("tooLarge");
    }
  }
  // (A standing refusal stays in the corner until a checkpoint lands.)
  if (
    edits.length > 0 &&
    projectSyncStatus !== "merged" &&
    projectSyncStatus !== "updated" &&
    !projectSaveRefused()
  ) {
    setProjectSyncStatus("saving");
  }

  const { status, data } = await syncApi(body);
  // The project may have been switched while the request was out.
  if (currentProject === null || currentProject.id !== project.id) return;

  if (status === 200 && data !== null) {
    await takeSyncAnswer(data, edits.length > 0, checkpointSerialized);
    return;
  }
  if (status === 404) {
    // The project is gone from the server (projects.ts decides what that
    // means for the plan on screen, after this round).
    noteProjectGone(currentStoredSnapshot());
    return;
  }
  if (status === 401) return; // Signed out meanwhile: the edits wait for the next sign-in.
  if (status === 413 && data?.error === "edit_too_large") {
    // One of the edits is over the server's cap (nothing was appended): the
    // biggest goes as several. One that cannot be split (a single op) is
    // beyond saving; it is dropped and said so, rather than sent for ever.
    const biggest = edits.reduce((a, b) => (editJsonBytes(b) > editJsonBytes(a) ? b : a));
    const parts = splitEdit(biggest);
    if (parts.length > 1 || biggest.ops.length < 2) {
      pendingEdits = pendingEdits.flatMap((edit) =>
        edit.id === biggest.id ? (parts.length > 1 ? parts : []) : [edit],
      );
      writePendingEdits();
      if (parts.length === 1) console.error("An edit too large for the server was dropped.");
    }
    scheduleSync(hasPendingEdits() ? 0 : SYNC_RETRY_MS);
    return;
  }
  const refusal = readProjectRefusal(status, data);
  if (refusal !== null) {
    // The checkpoint was too large (nothing was appended); the next round
    // sends the edits without one.
    noteProjectSaveRefused(refusal);
    syncCheckpointWanted = false;
    if (edits.length > 0) scheduleSync(SYNC_SEND_DELAY_MS);
    return;
  }
  setProjectSyncStatus("failed");
  scheduleSync(SYNC_RETRY_MS);
};

// An edit of ours applied again above someone else's: a set is simply set
// again, but an insert already in the list would stay where it was — so
// the item is taken out and put back after its anchor, behind what they
// inserted there, as the log's order has it.
const reapplyOps = (ops: EditOp[]): EditOp[] =>
  ops.flatMap((op): EditOp[] =>
    op.kind === "insert"
      ? [{ kind: "remove", path: op.path, item: op.item, after: op.after }, op]
      : [op],
  );

const readIncomingEdits = (value: unknown): SyncIncomingEdit[] =>
  Array.isArray(value)
    ? value.filter(
        (edit): edit is SyncIncomingEdit =>
          isPlainRecord(edit) &&
          typeof edit.seq === "number" &&
          typeof edit.opId === "string" &&
          typeof edit.clientId === "string" &&
          Array.isArray(edit.ops),
      )
    : [];

const takeSyncAnswer = async (
  data: RawSnapshot,
  sentEdits: boolean,
  checkpointSerialized: string | null,
) => {
  const project = currentProject;
  if (project === null) return;
  if (typeof data.headSeq !== "number" || typeof data.stateSeq !== "number") {
    setProjectSyncStatus("failed");
    scheduleSync(SYNC_RETRY_MS);
    return;
  }
  const headSeq = data.headSeq;
  takePresenceAnswer(data.peers, data.signals, data.iceServers);
  const acceptedSeqs = new Map<string, number>();
  if (Array.isArray(data.accepted)) {
    for (const entry of data.accepted) {
      if (isPlainRecord(entry) && typeof entry.opId === "string" && typeof entry.seq === "number") {
        acceptedSeqs.set(entry.opId, entry.seq);
      }
    }
  }
  const incoming = readIncomingEdits(data.edits);
  const summary = readProjectSummary(data.project);

  // Whatever happens below, the edits the server took are in the log.
  const settleAccepted = () => {
    pendingEdits = pendingEdits.filter((edit) => !acceptedSeqs.has(edit.id));
    writePendingEdits();
  };
  // A gesture begun while the request was out: nothing of others' is
  // applied under it (the DOM is ahead of the data); asked again shortly.
  // Everything stays pending (the accepted edits too, the server takes a
  // resend once), so the next answer still re-applies ours above theirs.
  if (isDragInProgress() && (data.truncated === true || incoming.length > 0)) {
    scheduleSync(SYNC_DRAG_WAIT_MS);
    return;
  }

  if (data.truncated === true) {
    // Too far behind for the log: the checkpoint and the edits since, taken
    // in as the server's version and merged with what is here.
    if (!(await takeServerVersion(summary, data.state, incoming, headSeq, acceptedSeqs))) {
      settleAccepted();
      return;
    }
    syncResyncWanted = false;
  } else {
    // Others' edits, in the server's order, each followed by this
    // computer's own edits that come after it in that order: the ones not
    // placed yet (they will be appended later than anything fetched now)
    // and the ones placed above it.
    const ours = new Set(pendingEdits.map((edit) => edit.id));
    const ops: EditOp[] = [];
    for (const edit of incoming) {
      if (edit.clientId === syncClientId() || ours.has(edit.opId) || acceptedSeqs.has(edit.opId)) {
        continue;
      }
      ops.push(...edit.ops);
      for (const mine of pendingEdits) {
        const placedAt = acceptedSeqs.get(mine.id);
        if (placedAt === undefined || placedAt > edit.seq) ops.push(...reapplyOps(mine.ops));
      }
    }
    if (ops.length > 0) {
      let shown: EditOp[] | null = null;
      adoptingServerSnapshot = true;
      try {
        shown = applyOpsToArrangement(
          ops.filter((op) => !isExportSettingsOp(op)),
          HISTORY_EDIT_RULES,
          false,
        );
        if (shown !== null) applyIncomingExportSettings(ops.filter(isExportSettingsOp));
      } finally {
        adoptingServerSnapshot = false;
      }
      if (shown === null) {
        // Others' edits could not be shown here: this computer must not
        // count itself as caught up (a checkpoint of its state would erase
        // their work). The next round asks for the server's version whole.
        settleAccepted();
        syncResyncWanted = true;
        setProjectSyncStatus("failed");
        scheduleSync(SYNC_RETRY_MS);
        return;
      }
    }
    project.syncedSeq = headSeq;
  }

  settleAccepted();
  // The others fetch what was just appended now, not on their next poll.
  if (acceptedSeqs.size > 0) nudgePeers(headSeq);
  const checkpointed = data.checkpointed === true;
  if (checkpointed || syncCheckpointWanted)
    syncCheckpointWanted = !checkpointed && hasPendingEdits();

  project.stateSeq = data.stateSeq;
  if (summary !== null) {
    takePublishStateFrom(summary);
    project.revision = summary.revision;
    const listed = projectList.find((candidate) => candidate.id === project.id);
    if (listed) Object.assign(listed, summary);
  }
  writeCurrentProjectRecord();
  // The base for a later merge is the very state the server took, not
  // what is stored now (an edit may have come in since).
  if (checkpointed && checkpointSerialized !== null) writeSyncedState(checkpointSerialized);
  renderProjectsPanel();

  // A refusal of the saved state stands until one lands; a round that
  // went through ends "saving" and "failed".
  if (checkpointed && projectSaveRefused()) setProjectSyncStatus("saved");
  else if (projectSyncStatus === "saving" || projectSyncStatus === "failed") {
    setProjectSyncStatus("saved");
  }
  renderProjectsStatus();

  if (hasPendingEdits()) {
    // Edited while the request was out, or more than fit in one request.
    scheduleSync(SYNC_SEND_DELAY_MS);
  } else if (
    project.syncedSeq !== null &&
    project.syncedSeq > project.stateSeq &&
    // A state known to be over the cap is tried again after an edit (it
    // may have shrunk), not on a timer.
    (projectSyncStatus !== "tooLarge" || sentEdits)
  ) {
    scheduleCheckpoint();
  }
};

// The server's version in whole (a project opened, a client too far behind):
// the checkpoint with the edits since applied, merged with what is here
// against the version both last agreed on (merge.ts); the merge is what
// shows, and what it adds to theirs goes out as this computer's one edit.
// With nothing edited here, theirs as it is.
const takeServerVersion = async (
  summary: ProjectSummary | null,
  rawState: unknown,
  incoming: SyncIncomingEdit[],
  headSeq: number,
  acceptedSeqs: Map<string, number>,
): Promise<boolean> => {
  const project = currentProject;
  if (project === null || summary === null || !isPlainRecord(rawState)) {
    setProjectSyncStatus("failed");
    scheduleSync(SYNC_RETRY_MS);
    return false;
  }
  const theirs = cloneData(rawState);
  // The log's edits on the checkpoint, in order — ours among them, as the
  // server placed them.
  applyEditOps(
    theirs,
    incoming.flatMap((edit) => edit.ops),
    HISTORY_EDIT_RULES,
    false,
  );
  // Still pending edits of ours are on screen (mine) but not in theirs;
  // the merge keeps them.
  const localSerialized = currentStoredSnapshot();
  const mine = localSerialized === null ? null : parseSerializedSnapshot(localSerialized);
  const base = readSyncedState();
  let wanted: RawSnapshot;
  let overridden = 0;
  const unplaced = pendingEdits.filter((edit) => !acceptedSeqs.has(edit.id));
  if (mine === null || unplaced.length === 0) {
    wanted = mine === null ? theirs : withNavigationOf(mine, theirs);
  } else {
    const merged = mergePersistedStates(
      base === null ? {} : parseSerializedSnapshot(base),
      mine,
      theirs,
    );
    wanted = merged.state;
    overridden = merged.overridden;
  }
  const readable = readPersistedSnapshot(wanted);
  const theirsReadable = readPersistedSnapshot(theirs);
  if (!readable || !theirsReadable) {
    setProjectSyncStatus("failed");
    scheduleSync(SYNC_RETRY_MS);
    return false;
  }
  adoptingServerSnapshot = true;
  try {
    showServerVersion(readable);
    markExportSettingsAsKnown();
  } finally {
    adoptingServerSnapshot = false;
  }
  // What the merge kept of ours beyond theirs is one edit; the pending
  // edits it stood for are spent (the accepted ones are in theirs).
  const difference = diffPersistedStates(
    liveUpdateStrip(theirsReadable, HISTORY_EDIT_RULES),
    JSON.parse(serializeHistorySnapshot()) as DataRecord,
    HISTORY_EDIT_RULES,
  );
  pendingEdits = difference.length > 0 ? [{ id: mintId("edit"), ops: difference }] : [];
  project.syncedSeq = headSeq;
  writeSyncedState(JSON.stringify(theirsReadable));
  lastMergeOverridden = overridden;
  setProjectSyncStatus(unplaced.length > 0 ? "merged" : "updated");
  return true;
};

// --- Checkpoints ---

const scheduleCheckpoint = () => {
  window.clearTimeout(syncCheckpointTimer);
  syncCheckpointTimer = window.setTimeout(() => {
    if (hasPendingEdits() || syncInFlight) return;
    void syncNow({ checkpoint: true });
  }, SYNC_CHECKPOINT_DELAY_MS);
};

// --- Creating the project from what is on screen ---

// No project yet for the account's arrangement: it becomes one, as a whole.
const createProjectFromArrangement = async () => {
  if (isArrangementEmpty() || lazyCreateSuppressed) return;
  const serialized = currentStoredSnapshot();
  if (serialized === null) return;
  if (snapshotOverLimit(serialized)) {
    noteProjectSaveRefused("tooLarge");
    return;
  }
  const created = await ensureProjectForSnapshot(serialized, defaultProjectName());
  if (created.outcome === "failed") {
    setProjectSyncStatus("failed");
    scheduleSync(SYNC_RETRY_MS);
  }
};

// --- What the rest of the app asks of this ---

// Sends what is pending, now, and lays the state down as the saved one.
// Awaited before anything that must not race a save: switching project,
// signing out, publishing. True when the server holds everything
// afterwards: nothing pending, the saved state at the log's head.
const flushProjectSave = async (): Promise<boolean> => {
  window.clearTimeout(syncSendTimer);
  window.clearTimeout(syncCheckpointTimer);
  if (getAccountUser() === null || projectSyncPaused) return false;
  // Two rounds at most: the first sends what is pending (and checkpoints
  // when nothing was out), the second checkpoints a state the first
  // could not (edits accepted only now).
  for (let round = 0; round < 2; round++) {
    await syncNow({ checkpoint: true });
    if (currentProject === null) return !hasPendingEdits() && projectSyncStatus === "saved";
    if (!hasPendingEdits() && currentProject.syncedSeq === currentProject.stateSeq) break;
    if (projectSyncStatus === "failed" || projectSaveRefused()) break;
  }
  renderProjectsStatus();
  return (
    currentProject !== null &&
    !hasPendingEdits() &&
    currentProject.syncedSeq === currentProject.stateSeq &&
    !projectSaveRefused()
  );
};

// Leaving the page: the pending edits go out with keepalive so they survive
// the tab closing. The answer can't be waited for; the edits stay stored,
// and the next load sends them again — the server takes each once. The
// same request says this tab is gone, so the others see it go at once.
const flushProjectSaveOnLeave = () => {
  if (currentProject === null || getAccountUser() === null || projectSyncPaused) return;
  if (!isDragInProgress()) {
    syncCollecting = true;
    try {
      commitEdit();
      sweepUnrecordedChanges();
      sweepExportSettings();
    } finally {
      syncCollecting = false;
    }
  }
  if (!hasPendingEdits() && !presenceIsAnnounced()) return;
  sendLeaveRequest(packEditsForRequest().edits);
};

// The request of a tab on its way out (closing, hiding, switching
// project): its presence row goes, and the edits given go with it. The
// answer is not waited for; the edits stay stored, and the next load sends
// them again — the server takes each once.
const sendLeaveRequest = (edits: SyncEdit[]) => {
  if (currentProject === null || getAccountUser() === null) return;
  const body = JSON.stringify({
    id: currentProject.id,
    clientId: syncClientId(),
    sinceSeq: currentProject.syncedSeq,
    edits: edits.map((edit) => ({ opId: edit.id, ops: edit.ops })),
    leave: true,
  });
  try {
    void fetch(SYNC_ENDPOINT, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body,
      keepalive: body.length <= SYNC_KEEPALIVE_MAX_BYTES,
    });
  } catch {
    // Nothing more to do on the way out.
  }
};

// Waits for a request out right now; nothing new is started.
const waitForSyncIdle = async () => {
  window.clearTimeout(syncSendTimer);
  if (syncInFlight) await syncInFlight.catch(() => undefined);
};

// A project just opened or taken over (projects.ts): its pending edits from
// a tab closed early, if any, and a first round to catch up.
const startSyncingProject = () => {
  if (currentProject === null) return;
  pendingEdits = readPendingEdits(currentProject.id);
  if (hasPendingEdits()) scheduleSync(0);
};

// How long until the next poll: quick while two tabs are being introduced,
// a few seconds when the project is shared or someone else is here, slow
// when alone.
const syncPollPace = (): number => {
  if (presenceSignalling()) return SYNC_POLL_SIGNALLING_MS;
  const shared =
    currentProject !== null &&
    (currentProject.memberCount > 0 || !currentProject.isOwner || presencePeerCount() > 0);
  return shared ? SYNC_POLL_SHARED_MS : SYNC_POLL_ALONE_MS;
};

// The poll timer set anew at the pace of now — also when the pace just
// changed (someone arrived, an introduction began: presence.ts), so the
// slow timer of a tab that was alone does not stand.
const armSyncPoll = () => {
  window.clearTimeout(syncPollTimer);
  syncPollTimer = window.setTimeout(syncPollTick, syncPollPace());
};

// The poll: others' edits, and publishing done elsewhere. Nothing is asked
// while a request is out (its answer tells the same), nor while hidden.
const syncPollTick = () => {
  armSyncPoll();
  if (currentProject === null || getAccountUser() === null || projectSyncPaused) return;
  if (syncInFlight || adoptingServerSnapshot) return;
  if (document.visibilityState !== "visible") return;
  void syncNow();
};

// Called from initProjects (projects.ts).
const initSync = () => {
  editsListener = onLocalEdit;
  syncPollTick();
  window.addEventListener("pagehide", () => {
    flushProjectSaveOnLeave();
    leavePresence(false);
  });
  document.addEventListener("visibilitychange", () => {
    if (document.visibilityState === "hidden") {
      // (Says this tab is gone; the connections to the others close with
      // it. A hidden tab's timers are throttled, so it holds nothing.)
      flushProjectSaveOnLeave();
      leavePresence(false);
    } else if (currentProject !== null && getAccountUser() !== null) {
      void syncNow();
    }
  });
};

// Opens a project from the server: the checkpoint and the edits since, in
// one request (projects.ts openProject). The pending edits of whatever was
// open before were sent by the caller. False when it could not be had.
const openProjectFromServer = async (id: string): Promise<boolean> => {
  // Here from this request on (the room on show is not known yet): who
  // else is comes back with the project, and the introductions begin.
  const announcing = presenceAnnouncing();
  if (announcing) presenceRequestSent();
  const { status, data } = await syncApi({
    id,
    clientId: syncClientId(),
    sinceSeq: null,
    edits: [],
    ...(announcing ? { presence: { roomId: null } } : {}),
  });
  if (status !== 200 || data === null) return false;
  const summary = readProjectSummary(data.project);
  const state = isPlainRecord(data.state) ? readPersistedSnapshot(data.state) : undefined;
  if (summary === null || !state || typeof data.headSeq !== "number") return false;
  // (adoptServerState lets go of the project left — its edits stay stored,
  // its presence is left.)
  if (!adoptServerState(summary, state)) return false;
  takePresenceAnswer(data.peers, data.signals, data.iceServers);
  // Edits left for this project earlier (a tab that switched away before
  // they went) are this tab's to send now.
  startSyncingProject();
  const incoming = readIncomingEdits(data.edits).flatMap((edit) => edit.ops);
  let shown: EditOp[] | null = [];
  adoptingServerSnapshot = true;
  try {
    if (incoming.length > 0) {
      shown = applyOpsToArrangement(
        incoming.filter((op) => !isExportSettingsOp(op)),
        HISTORY_EDIT_RULES,
        false,
      );
      if (shown !== null) {
        applyIncomingExportSettings(incoming.filter(isExportSettingsOp));
        saveStateNow();
      }
    }
    markExportSettingsAsKnown();
  } finally {
    adoptingServerSnapshot = false;
  }
  if (currentProject !== null && currentProject.id === summary.id) {
    if (shown === null) {
      // The edits since the checkpoint could not be shown: the project is
      // open at its checkpoint, not caught up — no checkpoint of this state
      // (it would erase those edits); the next round asks for the version
      // in whole.
      syncResyncWanted = true;
      setProjectSyncStatus("failed");
      scheduleSync(SYNC_RETRY_MS);
      return true;
    }
    currentProject.syncedSeq = data.headSeq;
    writeCurrentProjectRecord();
    if (data.headSeq > currentProject.stateSeq) scheduleCheckpoint();
  }
  return true;
};
