/**
 * Tests for the online 1 vs 1 lockstep layer (src/lib/multiplayer/online.ts).
 *
 * Run with: node --experimental-strip-types --test src/lib/multiplayer/online.test.ts
 *
 * The engine is pure TypeScript with no DOM imports, and OnlineNet's PeerJS
 * import is dynamic (only inside createRoom/joinRoom), so this file runs in
 * plain Node. PeerJS itself is NOT tested here: the two-browser smoke test
 * (smoke-online.mjs) covers the real connection.
 *
 * The determinism test below is the proof lockstep stands on: two matches
 * with the same seed, fed the same pad packets through two OnlineSessions,
 * must stay bit-identical for 600 steps.
 */
import { describe, it } from "node:test";
import assert from "node:assert/strict";
import {
  createOnlineMatch,
  isRoomCode,
  makeRoomCode,
  nextRotation,
  OnlineSession,
  queueAdd,
  queueRemove,
  roomCodeFromSearch,
  roomInviteLink,
  roomPeerId,
  shortPeerId,
  stateHash,
  snapshotMatch,
  restoreMatch,
  type NetMsg,
  type QueueEntry,
} from "./online.ts";
import {
  blankPad,
  stepMatch,
  stripEdges,
  type InputPad,
  type Match,
} from "../../game/engine.ts";
import { STEP } from "../../game/constants.ts";

/** Pad con bordes, como los calcula el componente (sample/commit). */
function scriptPad(
  step: number,
  side: "p0" | "p1",
  prev: { jump: boolean; attack: boolean; down: boolean },
): InputPad {
  let x = 0;
  let jump = false;
  let attack = false;
  let down = false;
  if (side === "p0") {
    x = step < 240 ? 1 : step < 360 ? -1 : 0;
    jump = step % 90 < 20;
    attack = step % 150 < 10;
  } else {
    x = step < 300 ? -1 : 1;
    jump = step % 110 < 15;
    attack = step % 130 < 12;
    down = step % 200 < 8;
  }
  const pad: InputPad = {
    x,
    jump,
    jumpPressed: jump && !prev.jump,
    jumpReleased: !jump && prev.jump,
    attack,
    attackPressed: attack && !prev.attack,
    attackReleased: !attack && prev.attack,
    down,
    downPressed: down && !prev.down,
  };
  prev.jump = jump;
  prev.attack = attack;
  prev.down = down;
  return pad;
}

/** Dos sesiones unidas por un cable en memoria (sin red). */
function linkedPair(seed: number): {
  host: OnlineSession;
  guest: OnlineSession;
  deliver: () => void;
} {
  const host = new OnlineSession(createOnlineMatch(seed, { left: "tizo", right: "lumi" }), "host");
  const guest = new OnlineSession(createOnlineMatch(seed, { left: "tizo", right: "lumi" }), "guest");
  const inbox: { to: OnlineSession; msg: NetMsg }[] = [];
  host.onHash = (step, hash) => inbox.push({ to: guest, msg: { t: "hash", step, hash } });
  guest.onHash = (step, hash) => inbox.push({ to: host, msg: { t: "hash", step, hash } });
  host.onDesync = () => {
    inbox.push({ to: guest, msg: { t: "snapshot", ...host.snapshot() } });
    host.clearResync();
  };
  guest.onDesync = () => inbox.push({ to: host, msg: { t: "needstate" } });
  const deliver = () => {
    while (inbox.length > 0) {
      const { to, msg } = inbox.shift()!;
      if (msg.t === "hash") to.receiveHash(msg.step, msg.hash);
      else if (msg.t === "snapshot") to.restore(msg);
      else if (msg.t === "needstate" && to === host) {
        inbox.push({ to: guest, msg: { t: "snapshot", ...host.snapshot() } });
        host.clearResync();
      }
    }
  };
  return { host, guest, deliver };
}

/** Un frame de intercambio: cada lado muestrea y envía su pad (n=2 pasos). */
function exchangeFrame(
  pair: ReturnType<typeof linkedPair>,
  frameStep: number,
  prev0: { jump: boolean; attack: boolean; down: boolean },
  prev1: { jump: boolean; attack: boolean; down: boolean },
): void {
  const pkt0 = pair.host.sendFrame(scriptPad(frameStep, "p0", prev0), 2);
  const pkt1 = pair.guest.sendFrame(scriptPad(frameStep, "p1", prev1), 2);
  assert.ok(pkt0 && pkt1, "sendFrame must produce a packet");
  pair.host.receivePad(pkt1.from, pkt1.n, pkt1.pad);
  pair.guest.receivePad(pkt0.from, pkt0.n, pkt0.pad);
  pair.host.runSteps();
  pair.guest.runSteps();
  pair.deliver();
}

describe("room codes", () => {
  it("generates 4 readable letters, no ambiguous characters", () => {
    for (let i = 0; i < 50; i++) {
      const code = makeRoomCode();
      assert.match(code, /^[A-HJ-KM-NP-Z2-9]{4}$/);
      assert.ok(isRoomCode(code));
      assert.equal(roomPeerId(code), `goalfighters-${code.toLowerCase()}`);
    }
  });

  it("rejects malformed codes", () => {
    assert.equal(isRoomCode("ABC"), false);
    assert.equal(isRoomCode("ABCDE"), false);
    assert.equal(isRoomCode("ABCO"), false); // O ambigua
    assert.equal(isRoomCode("AB1I"), false); // I ambigua
    assert.equal(isRoomCode(""), false);
    assert.equal(isRoomCode("kx7q"), true);
  });

  it("invite link carries the code in uppercase, ready to open", () => {
    assert.equal(
      roomInviteLink("abcd", "https://goalfighters.netlify.app/"),
      "https://goalfighters.netlify.app/?room=ABCD",
    );
    assert.equal(
      roomInviteLink("wxyz", "https://goalfighters.netlify.app/?room=AAAA#menu"),
      "https://goalfighters.netlify.app/?room=WXYZ",
    );
    assert.equal(
      roomInviteLink("abcd", "https://goalfighters.netlify.app/juego"),
      "https://goalfighters.netlify.app/juego?room=ABCD",
    );
  });

  it("reads the room code from the invite link (?room=XXXX)", () => {
    assert.equal(roomCodeFromSearch("?room=abcd"), "ABCD");
    assert.equal(roomCodeFromSearch("?room=ABCD&otro=1"), "ABCD");
    assert.equal(roomCodeFromSearch(""), null);
    assert.equal(roomCodeFromSearch("?room=ABC"), null);
    assert.equal(roomCodeFromSearch("?room=AB1D"), null);
    assert.equal(roomCodeFromSearch("?otro=ABCD"), null);
  });
});

describe("lockstep determinism (real engine)", () => {
  it("two sessions fed the same packets stay identical for 600 steps", () => {
    const pair = linkedPair(12345);
    const prev0 = { jump: false, attack: false, down: false };
    const prev1 = { jump: false, attack: false, down: false };
    // 304 frames: los primeros 4 no simulan nada (retraso de entrada), los
    // 300 restantes corren 2 pasos cada uno = 600 pasos.
    for (let f = 0; f < 304; f++) {
      exchangeFrame(pair, f * 2, prev0, prev1);
      assert.equal(pair.host.step, pair.guest.step, `steps diverged at frame ${f}`);
      assert.equal(
        stateHash(pair.host.match),
        stateHash(pair.guest.match),
        `hashes diverged at step ${pair.host.step}`,
      );
    }
    assert.equal(pair.host.step, 600);
    assert.equal(
      JSON.stringify(snapshotMatch(pair.host.match)),
      JSON.stringify(snapshotMatch(pair.guest.match)),
      "full snapshots must be identical after 600 steps",
    );
  });

  it("input delay holds the first steps until the buffer fills, then runs in sync", () => {
    const pair = linkedPair(777);
    const prev0 = { jump: false, attack: false, down: false };
    const prev1 = { jump: false, attack: false, down: false };
    // Los primeros 4 frames solo envían: el partido no simula hasta tener
    // el retraso de entrada completo (8 pasos por delante).
    for (let f = 0; f < 4; f++) {
      exchangeFrame(pair, f * 2, prev0, prev1);
      assert.equal(pair.host.step, 0, `step ran too early at frame ${f}`);
      assert.equal(pair.guest.step, 0);
    }
    exchangeFrame(pair, 8, prev0, prev1);
    assert.equal(pair.host.step, 2, "first steps should run once the buffer fills");
    assert.equal(pair.guest.step, 2);
    for (let f = 5; f < 20; f++) {
      exchangeFrame(pair, f * 2, prev0, prev1);
      assert.equal(pair.host.step, pair.guest.step, `steps diverged at frame ${f}`);
      assert.equal(
        stateHash(pair.host.match),
        stateHash(pair.guest.match),
        `hashes diverged at step ${pair.host.step}`,
      );
    }
    assert.equal(pair.host.step, 32);
  });

  it("stateHash is stable for the same state and changes when it moves", () => {
    const m = createOnlineMatch(99, { left: "tizo", right: "lumi" });
    const h0 = stateHash(m);
    assert.equal(stateHash(m), h0);
    stepMatch(m, { p0: blankPad(), p1: blankPad() }, STEP);
    assert.notEqual(stateHash(m), h0);
  });

  it("snapshot/restore is complete: the restored match continues identically", () => {
    const pair = linkedPair(777);
    const prev0 = { jump: false, attack: false, down: false };
    const prev1 = { jump: false, attack: false, down: false };
    for (let f = 0; f < 150; f++) exchangeFrame(pair, f * 2, prev0, prev1);
    assert.equal(pair.host.step, 292); // 150 frames menos 4 de retraso de entrada, 2 pasos por frame
    // Restaurar la foto del anfitrión en un partido nuevo con otra semilla.
    const fresh: Match = createOnlineMatch(1, { left: "tizo", right: "lumi" });
    restoreMatch(fresh, snapshotMatch(pair.host.match));
    assert.equal(stateHash(fresh), stateHash(pair.host.match));
    // Y seguir jugando con los mismos pads: los dos deben mantenerse
    // idénticos 120 pasos más (la foto está completa). Los dos se avanzan
    // paso a paso directo con los mismos pads, sin pasar por la sesión,
    // porque el retraso de entrada desalineaba el paso del anfitrión del
    // paso del guion y el restaurado se quedaba con otros pads.
    const prevA = { jump: false, attack: false, down: false };
    const prevB = { jump: false, attack: false, down: false };
    for (let f = 150; f < 210; f++) {
      const pads = {
        p0: scriptPad(f * 2, "p0", prevA),
        p1: scriptPad(f * 2, "p1", prevB),
      };
      stepMatch(pair.host.match, pads, STEP);
      stepMatch(pair.host.match, { p0: stripEdges(pads.p0), p1: stripEdges(pads.p1) }, STEP);
      stepMatch(fresh, pads, STEP);
      stepMatch(fresh, { p0: stripEdges(pads.p0), p1: stripEdges(pads.p1) }, STEP);
      assert.equal(stateHash(fresh), stateHash(pair.host.match), `frame ${f}`);
    }
  });

  it("a desync is detected and the host snapshot repairs it", () => {
    const pair = linkedPair(4242);
    const prev0 = { jump: false, attack: false, down: false };
    const prev1 = { jump: false, attack: false, down: false };
    for (let f = 0; f < 120; f++) exchangeFrame(pair, f * 2, prev0, prev1);
    assert.equal(pair.host.step, 232); // 120 frames menos 4 de retraso de entrada, 2 pasos por frame
    // Corromper al invitado a mano: la pelota salta a otro sitio.
    pair.guest.match.ball.x += 37;
    pair.guest.match.ball.vx = 500;
    // Seguir jugando: el hash del paso 360 debe delatar la diferencia.
    let repaired = false;
    const before = pair.guest.onDesync;
    pair.guest.onDesync = (step) => {
      repaired = true;
      before?.(step);
    };
    for (let f = 120; f < 200 && !repaired; f++) exchangeFrame(pair, f * 2, prev0, prev1);
    assert.ok(repaired, "the desync should have been detected by step 360");
    pair.deliver();
    assert.equal(
      stateHash(pair.guest.match),
      stateHash(pair.host.match),
      "guest must match the host after the snapshot",
    );
  });

  it("sendFrame stops when the match is more than 2 s behind (backpressure)", () => {
    const m = createOnlineMatch(5, { left: "tizo", right: "lumi" });
    const s = new OnlineSession(m, "host");
    const pad = blankPad();
    let sent = 0;
    while (s.sendFrame(pad, 2)) sent++;
    assert.equal(sent, 120, "240 steps of backlog, 2 per frame");
    assert.equal(s.sendFrame(pad, 2), null);
  });
});

describe("adaptive input delay and smooth catch-up", () => {
  it("setLatency only sets the network floor; jitter only seeds the starting delay", () => {
    const s = new OnlineSession(createOnlineMatch(9, { left: "tizo", right: "lumi" }), "guest");
    // 49 ms de ping con muchísimo jitter: antes daba d22 (183 ms de input).
    s.setLatency(49, 100, true);
    assert.equal(s.inputDelay, 8 + 6, "mínimo 8 + medio jitter medido como colchón");
    // Ya en marcha, el ping no sube nada por sí solo.
    const t = new OnlineSession(createOnlineMatch(9, { left: "tizo", right: "lumi" }), "guest");
    t.setLatency(49, 100, false);
    for (let i = 0; i < 20; i++) t.runSteps();
    assert.equal(t.inputDelay, 8);
    // Una red absurda sube el mínimo, pero nunca pasa del tope jugable.
    t.setLatency(5000, 500);
    for (let i = 0; i < 60; i++) t.runSteps();
    assert.equal(t.inputDelay, 30);
  });

  it("a late opponent pad raises the delay by how late it was; calm lowers it slowly", () => {
    const pair = linkedPair(77);
    const pad = blankPad();
    const { host, guest } = pair;
    for (let f = 0; f < 20; f++) {
      const a = host.sendFrame(pad, 2);
      const b = guest.sendFrame(pad, 2);
      assert.ok(a && b);
      host.receivePad(b.from, b.n, b.pad);
      guest.receivePad(a.from, a.n, a.pad);
      host.runSteps(Math.min(host.backlog, 6));
      guest.runSteps(Math.min(guest.backlog, 6));
    }
    assert.equal(host.inputDelay, 8);
    // El invitado "se cuelga" 12 frames: el anfitrión se queda esperando.
    const held: Array<{ from: number; n: number; pad: typeof pad }> = [];
    for (let f = 0; f < 12; f++) {
      host.sendFrame(pad, 2);
      const b = guest.sendFrame(pad, 2);
      assert.ok(b);
      held.push(b);
      host.runSteps(Math.min(host.backlog, 6));
    }
    assert.equal(host.lastRan, 0, "congelado esperando al rival");
    for (const b of held) host.receivePad(b.from, b.n, b.pad);
    for (let f = 0; f < 30; f++) host.runSteps(Math.min(host.backlog, 6));
    assert.ok(host.inputDelay > 8 + 5, `el retraso subió a ${host.inputDelay}`);
    const raised = host.inputDelay;
    for (let f = 0; f < 125; f++) {
      const a = host.sendFrame(pad, 2);
      const b = guest.sendFrame(pad, 2);
      if (a) guest.receivePad(a.from, a.n, a.pad);
      if (b) host.receivePad(b.from, b.n, b.pad);
      host.runSteps(Math.min(host.backlog, 6));
      guest.runSteps(Math.min(guest.backlog, 6));
    }
    assert.ok(host.inputDelay < raised, "bajó con la calma");
    assert.ok(host.inputDelay >= 8);
  });

  it("runSteps(maxSteps) caps the catch-up after a stall instead of jumping", () => {
    const pair = linkedPair(4242);
    const pad = blankPad();
    // 10 frames solo enviando (sin entregar): se acumula atraso.
    const packets: Array<{ from: number; n: number; pad: typeof pad }> = [];
    for (let f = 0; f < 10; f++) {
      const p0 = pair.host.sendFrame(pad, 2);
      const p1 = pair.guest.sendFrame(pad, 2);
      assert.ok(p0 && p1);
      packets.push(p1);
      pair.guest.receivePad(p0.from, p0.n, p0.pad);
    }
    for (const p of packets) pair.host.receivePad(p.from, p.n, p.pad);
    // 20 pasos enviados, retraso 8 => 12 pasos pendientes.
    assert.equal(pair.host.backlog, 12);
    pair.host.runSteps(3);
    assert.equal(pair.host.step, 3, "solo 3 pasos este frame");
    assert.equal(pair.host.lastRan, 3);
    pair.host.runSteps();
    assert.equal(pair.host.step, 12, "sin límite alcanza todo lo pendiente");
  });

  it("peers with DIFFERENT input delays stay bit-identical (delay is local only)", () => {
    const pair = linkedPair(31337);
    pair.guest.setLatency(180, 25); // el invitado espera más que el anfitrión
    let desyncs = 0;
    pair.host.onDesync = () => desyncs++;
    pair.guest.onDesync = () => desyncs++;
    const prev0 = { jump: false, attack: false, down: false };
    const prev1 = { jump: false, attack: false, down: false };
    for (let f = 0; f < 400; f++) {
      const pkt0 = pair.host.sendFrame(scriptPad(f * 2, "p0", prev0), 2);
      const pkt1 = pair.guest.sendFrame(scriptPad(f * 2, "p1", prev1), 2);
      assert.ok(pkt0 && pkt1);
      pair.host.receivePad(pkt1.from, pkt1.n, pkt1.pad);
      pair.guest.receivePad(pkt0.from, pkt0.n, pkt0.pad);
      pair.host.runSteps(Math.min(pair.host.backlog, 6));
      pair.guest.runSteps(Math.min(pair.guest.backlog, 6));
      pair.deliver();
    }
    assert.ok(pair.guest.inputDelay > pair.host.inputDelay);
    // Cada lado va por un paso distinto (el invitado espera más), así que no
    // se comparan "ahora": se comparan los hashes que cada uno registró en
    // los mismos pasos (cada 120). Y ninguno debe haber pedido resincronizar.
    assert.equal(desyncs, 0, "ningún desync pese a retrasos distintos");
    const hostLog = new Map(pair.host.hashLog.map((h) => [h.step, h.hash]));
    let compared = 0;
    for (const g of pair.guest.hashLog) {
      const h = hostLog.get(g.step);
      if (h !== undefined) {
        assert.equal(g.hash, h, `hash distinto en el paso ${g.step}`);
        compared++;
      }
    }
    assert.ok(compared >= 1, "hay al menos un paso común comparado");
    assert.ok(pair.host.step > 600 && pair.guest.step > 600);
  });

  it("beforeStep fires once per simulated step, before the state changes", () => {
    const pair = linkedPair(55);
    const seen: number[] = [];
    pair.host.beforeStep = () => seen.push(pair.host.match.ball.y);
    const prev0 = { jump: false, attack: false, down: false };
    const prev1 = { jump: false, attack: false, down: false };
    const y0 = pair.host.match.ball.y;
    for (let f = 0; f < 12; f++) exchangeFrame(pair, f * 2, prev0, prev1);
    assert.equal(seen.length, pair.host.step);
    assert.equal(seen[0], y0, "la primera captura es el estado inicial");
  });
});

describe("spectators (receiveSidePad)", () => {
  /** Tres sesiones unidas por un relevo en memoria: el anfitrión reenvía
   * los pads de los dos jugadores etiquetados por lado al espectador. */
  function trio(seed: number): {
    host: OnlineSession;
    guest: OnlineSession;
    spec: OnlineSession;
    deliver: () => void;
  } {
    const pair = linkedPair(seed);
    const spec = new OnlineSession(
      createOnlineMatch(seed, { left: "tizo", right: "lumi" }),
      "guest",
      null,
    );
    return { ...pair, spec };
  }

  /** Un frame de intercambio con espectador: los pads van a los tres. */
  function exchangeFrame3(
    t: ReturnType<typeof trio>,
    frameStep: number,
    prev0: { jump: boolean; attack: boolean; down: boolean },
    prev1: { jump: boolean; attack: boolean; down: boolean },
  ): void {
    const pkt0 = t.host.sendFrame(scriptPad(frameStep, "p0", prev0), 2);
    const pkt1 = t.guest.sendFrame(scriptPad(frameStep, "p1", prev1), 2);
    assert.ok(pkt0 && pkt1, "sendFrame must produce a packet");
    t.host.receivePad(pkt1.from, pkt1.n, pkt1.pad);
    t.guest.receivePad(pkt0.from, pkt0.n, pkt0.pad);
    // El anfitrión reenvía los dos pads etiquetados al espectador.
    t.spec.receiveSidePad("p0", pkt0.from, pkt0.n, pkt0.pad);
    t.spec.receiveSidePad("p1", pkt1.from, pkt1.n, pkt1.pad);
    t.host.runSteps();
    t.guest.runSteps();
    t.spec.runSteps();
    t.deliver();
  }

  it("a spectator fed labelled pads stays bit-identical for 600 steps", () => {
    const t = trio(12345);
    const prev0 = { jump: false, attack: false, down: false };
    const prev1 = { jump: false, attack: false, down: false };
    for (let f = 0; f < 304; f++) {
      exchangeFrame3(t, f * 2, prev0, prev1);
      assert.equal(t.spec.step, t.host.step, `spectator step diverged at frame ${f}`);
      assert.equal(
        stateHash(t.spec.match),
        stateHash(t.host.match),
        `spectator hash diverged at step ${t.host.step}`,
      );
    }
    assert.equal(t.spec.step, 600);
  });

  it("a spectator joining mid-match (snapshot + buffered pads) catches up in sync", () => {
    const pair = linkedPair(777);
    const prev0 = { jump: false, attack: false, down: false };
    const prev1 = { jump: false, attack: false, down: false };
    for (let f = 0; f < 150; f++) exchangeFrame(pair, f * 2, prev0, prev1);
    assert.equal(pair.host.step, 292);
    // El espectador entra a mitad: foto + pads en vuelo de los dos lados.
    const spec = new OnlineSession(
      createOnlineMatch(777, { left: "tizo", right: "lumi" }),
      "guest",
      null,
    );
    const snap = pair.host.snapshot();
    spec.restore(snap);
    for (const { step, p0, p1 } of pair.host.bufferedPads(snap.step)) {
      if (p0) spec.receiveSidePad("p0", step, 1, p0);
      if (p1) spec.receiveSidePad("p1", step, 1, p1);
    }
    assert.equal(stateHash(spec.match), stateHash(pair.host.match), "snapshot must match");
    // Seguir jugando con el relevo: el espectador no se queda atrás ni diverge.
    const t = { ...pair, spec };
    for (let f = 150; f < 300; f++) {
      exchangeFrame3(t, f * 2, prev0, prev1);
      assert.equal(spec.step, pair.host.step, `spectator step diverged at frame ${f}`);
      assert.equal(
        stateHash(spec.match),
        stateHash(pair.host.match),
        `spectator hash diverged at step ${pair.host.step}`,
      );
    }
  });

  it("after a resync the guest keeps playing in sync (no freeze)", () => {
    const pair = linkedPair(4242);
    const prev0 = { jump: false, attack: false, down: false };
    const prev1 = { jump: false, attack: false, down: false };
    for (let f = 0; f < 120; f++) exchangeFrame(pair, f * 2, prev0, prev1);
    assert.equal(pair.host.step, 232);
    // Corromper al invitado y dejar que el hash lo delate.
    pair.guest.match.ball.x += 37;
    pair.guest.match.ball.vx = 500;
    let repaired = false;
    const before = pair.guest.onDesync;
    pair.guest.onDesync = (step) => {
      repaired = true;
      before?.(step);
    };
    for (let f = 120; f < 200 && !repaired; f++) exchangeFrame(pair, f * 2, prev0, prev1);
    assert.ok(repaired, "the desync should have been detected");
    pair.deliver();
    assert.equal(
      stateHash(pair.guest.match),
      stateHash(pair.host.match),
      "guest must match the host after the snapshot",
    );
    // El anfitrión reenvía sus pads en vuelo (el invitado vuelve a muestrear
    // los suyos desde la foto): el partido SIGUE, no se congela.
    const snapStep = pair.guest.step;
    for (const { step, p0 } of pair.host.bufferedPads(snapStep)) {
      if (p0) pair.guest.receivePad(step, 1, p0);
    }
    const stepBefore = pair.guest.step;
    let desyncsAfter = 0;
    pair.guest.onDesync = () => desyncsAfter++;
    pair.host.onDesync = () => desyncsAfter++;
    for (let f = 200; f < 320; f++) exchangeFrame(pair, f * 2, prev0, prev1);
    assert.ok(pair.guest.step > stepBefore + 100, "the guest kept simulating after the resync");
    // Tras la foto el invitado corre unos pasos por detrás del anfitrión
    // (volvió a llenar su retraso de entrada): no se comparan "ahora", se
    // comparan los hashes que cada uno registró en los mismos pasos.
    assert.equal(desyncsAfter, 0, "no more desyncs after the repair");
    const hostLog = new Map(pair.host.hashLog.map((h) => [h.step, h.hash]));
    let compared = 0;
    for (const g of pair.guest.hashLog) {
      const h = hostLog.get(g.step);
      if (h !== undefined) {
        assert.equal(g.hash, h, `hash distinto en el paso ${g.step}`);
        compared++;
      }
    }
    assert.ok(compared >= 1, "hay al menos un paso común comparado tras la foto");
  });
});

describe("queue and rotation (pure rules)", () => {
  const a: QueueEntry = { id: "peer-aaaa", char: "mango" };
  const b: QueueEntry = { id: "peer-bbbb", char: "kiwi" };

  it("queueAdd appends in order and ignores a duplicate id", () => {
    const q1 = queueAdd([], a);
    assert.deepEqual(q1, [a]);
    assert.equal(queueAdd(q1, a), q1, "same array: duplicate ignored");
    assert.deepEqual(queueAdd(q1, b), [a, b]);
  });

  it("queueRemove drops only that id", () => {
    assert.deepEqual(queueRemove([a, b], a.id), [b]);
    assert.deepEqual(queueRemove([a, b], "peer-zzzz"), [a, b]);
  });

  it("nextRotation: winner stays, challenger takes the loser's side", () => {
    const r = nextRotation(3, 1, [a, b]);
    assert.ok(r);
    assert.equal(r.winnerSide, "p0");
    assert.equal(r.loserSide, "p1");
    assert.equal(r.challenger, a);
    assert.deepEqual(r.rest, [b]);
    const r2 = nextRotation(0, 2, [b]);
    assert.ok(r2);
    assert.equal(r2.winnerSide, "p1");
    assert.equal(r2.loserSide, "p0");
    assert.deepEqual(r2.rest, []);
  });

  it("nextRotation returns null without a queue or without a winner", () => {
    assert.equal(nextRotation(3, 1, []), null);
    assert.equal(nextRotation(2, 2, [a]), null);
  });

  it("shortPeerId shows the last 4 alphanumerics", () => {
    assert.equal(shortPeerId("goalfighters-ab12"), "AB12");
    assert.equal(shortPeerId("a1b2c3d4-e5f6-7890-abcd-ef1234567890"), "7890");
    assert.equal(shortPeerId("xy"), "XY");
  });
});



