// Undo/redo as edits (edits.ts): every entry is the list of operations one
// action made, each with the value it replaced, so undoing is applying the
// inverse and redoing is applying the ops again. Nothing is written by hand
// at the places that mutate the data: an action's start is marked by
// recordHistory() (the protocol below), which keeps a snapshot of the state
// as it was, and when the action is over (commitEdit) that snapshot is
// diffed against the live state.
//
// Protocol: every mutating action calls recordHistory() BEFORE it mutates.
// Drags record once at mousedown and are closed by the mouseup (data is
// only written then, interactions.ts); typing coalesces into one entry (see
// recordHistoryCoalesced); batchHistory makes several recording calls one
// entry. An edit is also closed before the state is saved, before a server
// copy is taken in, and before an undo or redo.
//
// Applying is guarded (edits.ts): an op only applies where the value still
// is what the edit left. So another person's change (a shared project,
// projects.ts) does not clear this stack: an undo of a field they changed
// since is simply skipped, and an entry that has nothing left to undo is
// dropped without a visible no-op. Any new edit clears redo.

const HISTORY_MAX_ENTRIES = 50;
const HISTORY_TYPING_COALESCE_MS = 1000;

type HistoryEntry = {
  id: string;
  ops: EditOp[];
  coalesceKey: string | undefined;
  committedAt: number;
  // Which room was on screen when the edit began and ended: not part of
  // the ops (navigation never is), but undo puts the user back in the room
  // the edit was made in, and redo in the room it ended in.
  view: { roomBefore: RoomId; roomAfter: RoomId };
};

type OpenEdit = {
  before: string;
  coalesceKey: string | undefined;
  roomBefore: RoomId;
  timer: number | undefined;
  startedAt: number;
  lastRecordedAt: number;
};

let undoStack: HistoryEntry[] = [];
let redoStack: HistoryEntry[] = [];
let openEdit: OpenEdit | undefined = undefined;

// Every edit made here — an action's, or what an undo or redo came to —
// is handed on, so the account's copy of a shared project (sync.ts) can
// send it to the others. Nothing listens in an anonymous session.
type CommittedEdit = { id: string; ops: EditOp[] };
let editsListener: ((edit: CommittedEdit) => void) | undefined;

// The arrangement as it last was through this file's hands (an edit
// committed, an undo shown, a version taken in): what a change made outside
// the protocol is caught against (sweepUnrecordedChanges). Undefined until
// the first look.
let lastKnownSnapshot: string | undefined = undefined;

// Nested recording guard: an action that calls several recording functions
// (the Delete key removing N selected tables, say) wraps them in
// batchHistory so the whole thing becomes a single undo step.
let historyBatchDepth = 0;

// Fields that never go into an edit: viewport (zoom/scroll — a Room's
// fields), the open room, the export panel and the current step are
// navigation, not arrangement edits; savedAt is a timestamp; zIndex is
// derived (rewritten on every table-list render, tables.ts).
const HISTORY_IGNORED_KEYS = new Set([
  "savedAt",
  "zoom",
  "scrollLeft",
  "scrollTop",
  "exportSettings",
  "currentStep",
  "currentRoomId",
  "zIndex",
]);

// Drops the open edit without an entry: for when the state it started from
// is about to be replaced under a gesture that never finished (a server
// copy taken in while the pointer was lost to another window, say). The
// diff would otherwise ascribe the whole replacement to this computer.
const discardOpenEdit = () => {
  if (!openEdit) return;
  if (openEdit.timer !== undefined) window.clearTimeout(openEdit.timer);
  openEdit = undefined;
};

// Opening a project file or another project replaces the arrangement the
// way a reload would: nothing before it is undoable.
const clearHistory = () => {
  undoStack = [];
  redoStack = [];
  discardOpenEdit();
  lastKnownSnapshot = undefined;
};

// The live arrangement is accounted for: whatever it is now is the state
// to catch later changes against. Called by whatever changes it on purpose
// outside an edit of this computer's (a version from elsewhere shown).
const markArrangementAsKnown = () => {
  lastKnownSnapshot = serializeHistorySnapshot();
};

// A change made without recordHistory (a mutation that bypasses the
// protocol) would never reach the project's log, and the copies would
// drift apart until the next checkpoint. Before every round with the
// server (sync.ts) the live state is compared with the last one accounted
// for; a difference becomes an edit like any other — undoable, and sent.
// Not under a gesture or an open edit: those are not over yet.
const sweepUnrecordedChanges = () => {
  if (openEdit || historyBatchDepth > 0 || isDragInProgress()) return;
  const now = serializeHistorySnapshot();
  if (lastKnownSnapshot === undefined) {
    lastKnownSnapshot = now;
    return;
  }
  if (now === lastKnownSnapshot) return;
  const from = lastKnownSnapshot;
  lastKnownSnapshot = now;
  recordUnrecordedChange(from, now);
};

// The difference between two states of the arrangement becomes an edit:
// an undo entry (the room on show for both ends) and, through the
// listener, something to send.
const recordUnrecordedChange = (fromSerialized: string, toSerialized: string) => {
  const ops = diffPersistedStates(
    JSON.parse(fromSerialized) as DataRecord,
    JSON.parse(toSerialized) as DataRecord,
    HISTORY_EDIT_RULES,
  );
  if (ops.length === 0) return;
  redoStack = [];
  const id = mintId("edit");
  undoStack.push({
    id,
    ops,
    coalesceKey: undefined,
    committedAt: Date.now(),
    view: { roomBefore: currentRoomId, roomAfter: currentRoomId },
  });
  if (undoStack.length > HISTORY_MAX_ENTRIES) undoStack.shift();
  markAnalyticsDirty();
  editsListener?.({ id, ops });
};

// A fresh chair has no isHidden where a loaded one has false (persistence.ts).
const HISTORY_EDIT_RULES: EditRules = {
  ignoredKeys: HISTORY_IGNORED_KEYS,
  defaults: { isHidden: false },
};

const serializeHistorySnapshot = (): string =>
  JSON.stringify(buildPersistedState(), (key, value) =>
    HISTORY_IGNORED_KEYS.has(key) ? undefined : value,
  );

const scheduleCommit = (delay: number) => {
  if (!openEdit) return;
  if (openEdit.timer !== undefined) window.clearTimeout(openEdit.timer);
  openEdit.timer = window.setTimeout(() => {
    if (openEdit) openEdit.timer = undefined;
    commitEdit();
  }, delay);
};

const beginEdit = (coalesceKey: string | undefined) => {
  openEdit = {
    before: serializeHistorySnapshot(),
    coalesceKey,
    roomBefore: currentRoomId,
    timer: undefined,
    startedAt: Date.now(),
    lastRecordedAt: Date.now(),
  };
  // A click or key that mutates at once is over as soon as the handler
  // returns; a drag is not, and the timer finds it still in progress
  // (commitEdit) and leaves it to the mouseup.
  scheduleCommit(coalesceKey === undefined ? 0 : HISTORY_TYPING_COALESCE_MS);
};

const recordHistory = () => {
  if (historyBatchDepth > 0) return;
  commitEdit();
  // Still open after that: a gesture is in progress (a key pressed
  // mid-drag, say). The new action joins it rather than losing its start.
  if (openEdit) return;
  beginEdit(undefined);
};

// For per-keystroke edits (name inputs): the first keystroke opens the
// edit; further keystrokes on the same field within
// HISTORY_TYPING_COALESCE_MS of the previous one keep it open, so one undo
// reverts the whole typing burst rather than one letter.
const recordHistoryCoalesced = (key: string) => {
  if (historyBatchDepth > 0) return;
  const now = Date.now();
  if (
    openEdit &&
    openEdit.coalesceKey === key &&
    now - openEdit.lastRecordedAt < HISTORY_TYPING_COALESCE_MS
  ) {
    openEdit.lastRecordedAt = now;
    scheduleCommit(HISTORY_TYPING_COALESCE_MS);
    return;
  }
  commitEdit();
  if (openEdit) return;
  beginEdit(key);
};

const batchHistory = (action: () => void) => {
  recordHistory();
  historyBatchDepth++;
  try {
    action();
  } finally {
    historyBatchDepth--;
  }
  commitEdit();
};

// The gestures touch.ts knows, plus panning the room.
const isDragInProgress = () => isAnyDragActive() || moveRoom;

// Closes the open edit: what changed since recordHistory becomes an entry.
// Refused mid-gesture (the DOM is ahead of the data until the mouseup
// writes it) and inside a batch; the mouseup and the batch's end call again.
const commitEdit = () => {
  if (!openEdit || historyBatchDepth > 0 || isDragInProgress()) return;
  const edit = openEdit;
  openEdit = undefined;
  if (edit.timer !== undefined) window.clearTimeout(edit.timer);

  // A change made outside the protocol between the last state accounted
  // for and this edit's start is its own edit first (see
  // sweepUnrecordedChanges); it must not vanish under this one.
  if (lastKnownSnapshot !== undefined && lastKnownSnapshot !== edit.before) {
    recordUnrecordedChange(lastKnownSnapshot, edit.before);
  }
  const before = JSON.parse(edit.before) as DataRecord;
  const afterSerialized = serializeHistorySnapshot();
  const after = JSON.parse(afterSerialized) as DataRecord;
  lastKnownSnapshot = afterSerialized;
  const ops = diffPersistedStates(before, after, HISTORY_EDIT_RULES);
  // A click that only selected a table records like any drag; it must not
  // cost an undo step, nor make the redo branch stale.
  if (ops.length === 0) return;

  redoStack = [];
  const now = Date.now();
  const top = undoStack[undoStack.length - 1];
  // One edit, one id: the entry's, or this one for the later half of a
  // typing burst appended to its entry.
  const editId = mintId("edit");
  // A typing burst that a save closed halfway (saveStateNow commits) goes
  // on in the same entry: the next keystroke opened this edit right after
  // that commit. (Judged from the edit's start, not from now — the burst's
  // own timer closes it a whole coalesce window after the last keystroke.)
  if (
    edit.coalesceKey !== undefined &&
    top &&
    top.coalesceKey === edit.coalesceKey &&
    edit.startedAt - top.committedAt < HISTORY_TYPING_COALESCE_MS
  ) {
    top.ops.push(...ops);
    top.committedAt = now;
    top.view.roomAfter = currentRoomId;
  } else {
    undoStack.push({
      id: editId,
      ops,
      coalesceKey: edit.coalesceKey,
      committedAt: now,
      view: { roomBefore: edit.roomBefore, roomAfter: currentRoomId },
    });
    if (undoStack.length > HISTORY_MAX_ENTRIES) undoStack.shift();
  }
  markAnalyticsDirty();
  editsListener?.({ id: editId, ops });
};

// Pops entries until one still has something to apply: an entry whose
// every op is skipped (its fields changed since, or a recorded action that
// turned out to be a no-op) must not cost the user an undo press that
// visibly does nothing.
const applyHistoryEntry = (
  from: HistoryEntry[],
  to: HistoryEntry[],
  opsOf: (entry: HistoryEntry) => EditOp[],
  roomOf: (entry: HistoryEntry) => RoomId,
) => {
  while (from.length > 0) {
    const entry = from.pop()!;
    // Applied with the guard (edits.ts): only where the value still is
    // what the edit left. The result is shown with only what differs
    // changed on screen (liveUpdate.ts), and that difference is the edit
    // this undo or redo made, sent on like any other.
    const shown = applyOpsToArrangement(opsOf(entry), HISTORY_EDIT_RULES, true, roomOf(entry));
    // An entry whose result cannot be shown is dropped (nothing changed);
    // it must not sit on the other stack as if it had been applied.
    if (shown === null) return;
    if (shown.length === 0) continue;
    to.push(entry);
    markAnalyticsDirty();
    editsListener?.({ id: mintId("edit"), ops: shown });
    return;
  }
};

const undo = () => {
  // A drag is only known here: it records at mousedown, and the edit itself
  // is closed by committing now (which also clears any redo branch).
  commitEdit();
  applyHistoryEntry(
    undoStack,
    redoStack,
    (entry) => invertEditOps(entry.ops),
    (entry) => entry.view.roomBefore,
  );
};

const redo = () => {
  // An edit made after the undo means the redo branch no longer applies;
  // committing it clears the branch.
  commitEdit();
  applyHistoryEntry(
    redoStack,
    undoStack,
    (entry) => entry.ops,
    (entry) => entry.view.roomAfter,
  );
};

// Inside a text field the browser's own text undo should win — the user is
// editing that text, not the arrangement. A focused checkbox or button has
// no text to undo, so the shortcut still reaches us there.
const NON_TEXT_INPUT_TYPES = [
  "checkbox",
  "radio",
  "button",
  "submit",
  "reset",
  "range",
  "color",
  "file",
];
const isTextFieldFocused = () => {
  const el = document.activeElement;
  if (!el) return false;
  if (el.tagName === "INPUT") return !NON_TEXT_INPUT_TYPES.includes((el as HTMLInputElement).type);
  return el.tagName === "TEXTAREA" || (el as HTMLElement).isContentEditable;
};

// The save closes the open edit first, so what is saved is what the entry
// says (persistence.ts calls through this seam; the guests' page loads
// persistence.ts without this file).
beforeStateSaved = commitEdit;

$(() => {
  // Drags write their data in interactions.ts's mouseup handler on #body;
  // this one runs after it (same element, bound later: this file loads
  // after interactions.ts) and closes the edit the mousedown opened.
  $("#body").on("mouseup", () => commitEdit());

  document.addEventListener("keydown", (e) => {
    if (!(e.metaKey || e.ctrlKey) || e.altKey || !e.key) return;
    const key = e.key.toLowerCase();
    // Cmd/Ctrl+Shift+Z and Ctrl+Y both redo (Mac and Windows conventions).
    const isRedo = key === "y" || (key === "z" && e.shiftKey);
    const isUndo = key === "z" && !e.shiftKey;
    if (!isRedo && !isUndo) return;

    if (isTextFieldFocused()) return;
    if (isModalOverlayOpen()) return;
    // Mid-gesture the DOM is ahead of the data; let the mouseup commit first.
    if (isDragInProgress()) return;

    e.preventDefault();
    if (isRedo) redo();
    else undo();
  });
});
