/**
 * Tests for the Goal Fighters engine (src/game/engine.ts) and its seeded RNG.
 *
 * Run with: node --experimental-strip-types --test src/game/engine.test.ts
 * (same runner as the rest of the repo — see package.json "test").
 *
 * The engine is pure TypeScript with no DOM or framework imports, so it
 * runs in plain Node. The key properties under test are the 1v1 contract,
 * elevated-goal scoring and frame-safe arena collisions.
 */
import { describe, it } from "node:test";
import assert from "node:assert/strict";
import {
  blankPad,
  bubbleY,
  checkGoal,
  createMatch,
  resolveArena,
  shieldDiscFor,
  shieldDiscs,
  shotVelocity,
  stepMatch,
  type Match,
} from "./engine.ts";
import { stateHash } from "../lib/multiplayer/online.ts";

import { createRng, nextRand } from "./rng.ts";
import { BALL, JUMP, KICK, PLAYER, POWERUP, STEP, WORLD } from "./constants.ts";
import { crowdDanger } from "./audio.ts";
import { CHARACTERS, getCharacter } from "./characters.ts";

const PADS = { p0: blankPad(), p1: blankPad() };
const MID_GOAL = (WORLD.goalTop + WORLD.goalBottom) / 2;

function step(m: Match, n: number) {
  for (let i = 0; i < n; i++) stepMatch(m, PADS, STEP);
}

/** Canonical snapshot of everything the simulation can change. */
function snapshot(m: Match): string {
  return JSON.stringify({
    ball: m.ball,
    fighters: m.fighters.map((f) => ({
      x: f.x,
      y: f.y,
      vx: f.vx,
      vy: f.vy,
      atk: f.atk,
      stun: f.stun,
    })),
    particles: m.particles.length,
    scoreL: m.scoreL,
    scoreR: m.scoreR,
    time: m.time,
    phase: m.phase,
    rng: m.rng.s,
  });
}

describe("createMatch (1 vs 1)", () => {
  it("starts a cpu match in play, 0-0, 120 s, ball at centre", () => {
    const m = createMatch({ mode: "cpu", difficulty: "normal", seed: 7 });
    assert.equal(m.phase, "play");
    assert.equal(m.scoreL, 0);
    assert.equal(m.scoreR, 0);
    assert.equal(m.time, 120);
    assert.equal(m.fighters.length, 2);
    assert.equal(m.ball.x, WORLD.w / 2);
    assert.equal(m.ball.y, BALL.kickoffY);
    assert.ok(m.ball.y >= 180 && m.ball.y <= 220, "kickoff ball must start in the air");
    assert.equal(m.kickoffGrace, BALL.kickoffGrace);
    assert.equal(m.seed, 7);
  });

  it("always creates exactly one fighter per team in every mode", () => {
    for (const mode of ["cpu", "demo", "online"] as const) {
      const fighters = createMatch({ mode, difficulty: "normal", seed: 1 }).fighters;
      assert.equal(fighters.length, 2, `${mode} must be 1v1`);
      assert.equal(fighters.filter((f) => f.team === "left").length, 1, mode);
      assert.equal(fighters.filter((f) => f.team === "right").length, 1, mode);
      assert.equal("role" in fighters[0], false, "roles were removed");
    }
  });

  it("uses the selected roster characters and never repeats one", () => {
    assert.equal(CHARACTERS.length, 8);
    assert.equal(new Set(CHARACTERS.map((c) => c.id)).size, 8);
    const picked = createMatch({
      mode: "online",
      difficulty: "normal",
      seed: 4,
      characters: { left: "mango", right: "pico" },
    });
    assert.equal(picked.fighters[0].character, "mango");
    assert.equal(picked.fighters[0].name, getCharacter("mango").name);
    assert.equal(picked.fighters[1].character, "pico");
    assert.equal(picked.fighters[1].name, getCharacter("pico").name);

    const duplicate = createMatch({
      mode: "cpu",
      difficulty: "normal",
      seed: 4,
      characters: { left: "kiwi", right: "kiwi" },
    });
    assert.notEqual(duplicate.fighters[0].character, duplicate.fighters[1].character);
  });

  it("uses the expected human/bot control split", () => {
    const cpu = createMatch({ mode: "cpu", difficulty: "normal", seed: 1 });
    assert.deepEqual(cpu.fighters.map((f) => f.control), ["p0", "bot"]);
    const online = createMatch({ mode: "online", difficulty: "normal", seed: 1 });
    assert.deepEqual(online.fighters.map((f) => f.control), ["p0", "p1"]);
    const demo = createMatch({ mode: "demo", difficulty: "normal", seed: 1 });
    assert.deepEqual(demo.fighters.map((f) => f.control), ["bot", "bot"]);
  });

  it("cuelga la portería bajo la grada y mantiene una abertura de 140 px", () => {
    assert.ok(WORLD.goalTop > WORLD.standBottom);
    assert.equal(WORLD.goalTop, 260);
    assert.equal(WORLD.goalBottom, 400);
    assert.equal(WORLD.goalBottom - WORLD.goalTop, 140);
  });

  it("works without an explicit seed", () => {
    const m = createMatch({ mode: "cpu", difficulty: "normal" });
    assert.equal(typeof m.seed, "number");
    assert.equal(m.fighters.length, 2);
  });
});

describe("determinism (seeded RNG)", () => {
  it("same seed + same inputs = identical match after 120 steps", () => {
    const a = createMatch({ mode: "cpu", difficulty: "hard", seed: 12345 });
    const b = createMatch({ mode: "cpu", difficulty: "hard", seed: 12345 });
    step(a, 120);
    step(b, 120);
    assert.equal(snapshot(a), snapshot(b));
    assert.equal(a.rng.s, b.rng.s);
  });

  it("different seeds diverge", () => {
    const a = createMatch({ mode: "cpu", difficulty: "hard", seed: 1 });
    const b = createMatch({ mode: "cpu", difficulty: "hard", seed: 2 });
    step(a, 600);
    step(b, 600);
    assert.notEqual(snapshot(a), snapshot(b));
  });

  it("nextRand is stable per seed and stays in [0, 1)", () => {
    const a = createRng(42);
    const b = createRng(42);
    for (let i = 0; i < 50; i++) {
      const v = nextRand(a);
      assert.equal(v, nextRand(b));
      assert.ok(v >= 0 && v < 1);
    }
    assert.notEqual(nextRand(createRng(1)), nextRand(createRng(2)));
  });
});

describe("stepMatch", () => {
  it("applies gravity to the ball (local mode, no input)", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 3 });
    const y0 = m.ball.y;
    step(m, 30);
    assert.ok(m.ball.y > y0 + 40, `ball should fall: ${y0} -> ${m.ball.y}`);
    assert.ok(m.ball.vy > 0);
  });

  it("counts the match clock down", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 3 });
    step(m, 120);
    assert.ok(m.time < 120 && m.time > 118, `time should be ~119, got ${m.time}`);
  });

  it("keeps both fighters in the field, never inside the elevated goals", () => {
    const m = createMatch({ mode: "cpu", difficulty: "normal", seed: 9 });
    step(m, 600);
    for (const f of m.fighters) {
      assert.ok(f.x >= 0 && f.x <= WORLD.w, `fighter x out of bounds: ${f.x}`);
      assert.ok(f.y <= WORLD.ground - PLAYER.hh + 0.01, `fighter y below ground: ${f.y}`);
      if (f.team === "left") assert.ok(f.x >= WORLD.mouth + PLAYER.hw - 0.01, `left fighter in goal: ${f.x}`);
      else assert.ok(f.x <= WORLD.w - WORLD.mouth - PLAYER.hw + 0.01, `right fighter in goal: ${f.x}`);
    }
    assert.ok(m.ball.x >= 0 && m.ball.x <= WORLD.w);
  });

  it("resets to a 1v1 kickoff after a goal while keeping the score", () => {
    const m = createMatch({ mode: "cpu", difficulty: "normal", seed: 11 });
    m.ball.x = WORLD.mouth - 10;
    m.ball.y = MID_GOAL;
    checkGoal(m);
    assert.equal(m.phase, "goal");
    assert.equal(m.scoreR, 1);
    step(m, Math.ceil(1.9 / STEP));
    assert.equal(m.phase, "play");
    assert.equal(m.scoreR, 1);
    assert.equal(m.fighters.length, 2);
    assert.equal(m.ball.x, WORLD.w / 2);
  });

  it("resets the camera to the kickoff framing after a goal", () => {
    const m = createMatch({ mode: "cpu", difficulty: "normal", seed: 11 });
    m.ball.x = WORLD.mouth - 10;
    m.ball.y = MID_GOAL;
    checkGoal(m);
    assert.equal(m.phase, "goal");
    // Cámara enfocada en la red (como queda tras el gol).
    m.camX = 800;
    m.camViewW = 300;
    m.camReady = true;
    step(m, Math.ceil(1.9 / STEP));
    assert.equal(m.phase, "play");
    assert.equal(m.ball.x, WORLD.w / 2);
    // El saque reencuadra de inmediato: sin esto la cámara seguía en la red
    // y el balón "saltaba" al reencuadrar.
    assert.equal(m.camX, -1);
    assert.equal(m.camViewW, 0);
    assert.equal(m.camReady, false);
  });
});

describe("pelota en el saque", () => {
  it("aparece centrada, en el aire y rebota varias veces antes de reposar", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 13 });
    assert.equal(m.ball.x, WORLD.w / 2);
    assert.ok(m.ball.y >= 180 && m.ball.y <= 220);
    let bounces = 0;
    let prevVy = m.ball.vy;
    let restingFrames = 0;
    for (let i = 0; i < 1200; i++) {
      const beforeVy = m.ball.vy;
      stepMatch(m, PADS, STEP);
      if (beforeVy > 45 && m.ball.vy < 0 && m.ball.y + m.ball.r >= WORLD.ground - 2) {
        bounces++;
      }
      if (
        Math.abs(m.ball.vy) < 0.01 &&
        Math.abs(m.ball.vx) < 0.01 &&
        m.ball.y + m.ball.r >= WORLD.ground - 0.6
      ) {
        restingFrames++;
      } else {
        restingFrames = 0;
      }
      prevVy = m.ball.vy;
    }
    assert.ok(bounces >= 2, `expected at least 2 bounces, got ${bounces}`);
    assert.ok(restingFrames > 20, "ball should settle on the floor");
    assert.equal(m.ball.x, WORLD.w / 2);
    assert.equal(prevVy, 0);
  });

  it("protege el primer instante con gracia sin congelar la pelota", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 14 });
    const y0 = m.ball.y;
    step(m, 10);
    assert.ok(m.ball.y > y0 + 1, "ball must already be falling during kickoff grace");
    assert.ok(m.kickoffGrace > 0);
  });
});

describe("vuelo y tiros", () => {
  it("en vuelo libre x es lineal e y es una parábola exacta", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 15 });
    m.kickoffGrace = 0;
    m.fighters[0].x = 100;
    m.fighters[1].x = 940;
    m.ball.x = 400;
    m.ball.y = 250;
    m.ball.vx = 300;
    m.ball.vy = -400;
    const x0 = m.ball.x;
    const y0 = m.ball.y;
    const vx0 = m.ball.vx;
    const vy0 = m.ball.vy;
    const frames = 30;
    step(m, frames);
    const t = frames * STEP;
    assert.ok(Math.abs(m.ball.x - (x0 + vx0 * t)) < 1e-7, "x must advance linearly");
    assert.ok(
      Math.abs(m.ball.y - (y0 + vy0 * t + 0.5 * BALL.gravity * t * t)) < 1e-7,
      "y must follow the parabolic formula",
    );
    assert.ok(Math.abs(m.ball.vy - (vy0 + BALL.gravity * t)) < 1e-7);
    assert.equal(m.ball.vx, vx0);
  });

  it("golpe normal y cargado usan los ángulos y rapideces definidos", () => {
    for (const [angle, speed] of [
      [KICK.normalAngle, KICK.normalSpeed],
      [KICK.chargedAngle, KICK.chargedSpeed],
    ]) {
      const shot = shotVelocity(angle, speed, 1);
      const measuredAngle = (Math.atan2(-shot.vy, shot.vx) * 180) / Math.PI;
      assert.ok(Math.abs(measuredAngle - angle) < 1e-9);
      assert.ok(Math.abs(Math.hypot(shot.vx, shot.vy) - speed) < 1e-9);
    }
    const left = shotVelocity(KICK.normalAngle, KICK.normalSpeed, -1);
    assert.ok(left.vx < 0 && left.vy < 0);
  });

  it("un tiro cargado desde el centro llega a la ventana rival sin tocar el techo", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 16 });
    m.kickoffGrace = 0;
    m.fighters[0].x = 130;
    m.fighters[1].x = 910;
    m.ball.x = WORLD.w / 2;
    m.ball.y = WORLD.ground - WORLD.ballR;
    const shot = shotVelocity(KICK.chargedAngle, KICK.chargedSpeed, 1);
    m.ball.vx = shot.vx;
    m.ball.vy = shot.vy;
    let apex = m.ball.y;
    for (let i = 0; i < 180 && m.phase === "play"; i++) {
      stepMatch(m, PADS, STEP);
      apex = Math.min(apex, m.ball.y);
    }
    assert.equal(m.scoreL, 1);
    assert.equal(m.phase, "goal");
    assert.ok(apex > WORLD.ceil + WORLD.ballR, `shot touched ceiling: ${apex}`);
  });
});

describe("doble salto", () => {
  it("permite un segundo salto, bloquea el tercero y se recarga al aterrizar", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 17 });
    const p = m.fighters[0];
    const first = { ...blankPad(), jump: true, jumpPressed: true };
    stepMatch(m, { p0: first, p1: blankPad() }, STEP);
    assert.equal(p.grounded, false);
    assert.equal(p.jumpsLeft, 1);
    stepMatch(m, { p0: blankPad(), p1: blankPad() }, STEP);

    const second = { ...blankPad(), jump: true, jumpPressed: true };
    stepMatch(m, { p0: second, p1: blankPad() }, STEP);
    assert.equal(p.jumpsLeft, 0);
    assert.ok(p.vy < JUMP.secondVy * 0.85, `second jump too weak: ${p.vy}`);

    stepMatch(m, { p0: blankPad(), p1: blankPad() }, STEP);
    const beforeThird = p.vy;
    const third = { ...blankPad(), jump: true, jumpPressed: true };
    stepMatch(m, { p0: third, p1: blankPad() }, STEP);
    assert.equal(p.jumpsLeft, 0);
    assert.ok(p.vy > beforeThird, "third press must not add upward velocity");

    for (let i = 0; i < 600 && !p.grounded; i++) {
      stepMatch(m, { p0: blankPad(), p1: blankPad() }, STEP);
    }
    assert.equal(p.grounded, true);
    assert.equal(p.jumpsLeft, 2);
  });
});

describe("checkGoal (elevated window only)", () => {
  it("scores for the right team when the whole ball crosses the left opening", () => {
    const m = createMatch({ mode: "cpu", difficulty: "normal", seed: 5 });
    m.ball.x = WORLD.mouth - 18;
    m.ball.y = MID_GOAL;
    checkGoal(m);
    assert.equal(m.scoreR, 1);
    assert.equal(m.scoreL, 0);
    assert.equal(m.phase, "goal");
    assert.equal(m.banner, "¡GOL!");
  });

  it("scores for the left team when the ball enters the right opening", () => {
    const m = createMatch({ mode: "cpu", difficulty: "normal", seed: 5 });
    m.ball.x = WORLD.w - WORLD.mouth + 18;
    m.ball.y = MID_GOAL;
    checkGoal(m);
    assert.equal(m.scoreL, 1);
    assert.equal(m.phase, "goal");
  });

  it("scores a real 1/120 s shot that crosses the window", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 21 });
    m.ball.x = WORLD.mouth + 40;
    m.ball.y = MID_GOAL;
    m.ball.vx = -500;
    m.ball.vy = 0;
    step(m, 40);
    assert.equal(m.scoreR, 1);
    assert.equal(m.phase, "goal");
  });

  it("does not score by rolling along the floor under the goal", () => {
    const m = createMatch({ mode: "cpu", difficulty: "normal", seed: 5 });
    m.ball.x = WORLD.mouth - 24;
    m.ball.y = WORLD.ground - WORLD.ballR;
    m.ball.vx = -900;
    checkGoal(m);
    assert.equal(m.scoreR, 0);
    assert.equal(m.phase, "play");
  });

  it("does not score above the crossbar or half-through the lip", () => {
    const m = createMatch({ mode: "cpu", difficulty: "normal", seed: 5 });
    m.ball.x = WORLD.mouth - 18;
    m.ball.y = WORLD.goalTop - 4;
    checkGoal(m);
    m.ball.y = WORLD.goalTop + 10;
    checkGoal(m);
    assert.equal(m.scoreR, 0);
    assert.equal(m.phase, "play");
  });

  it("flags an own goal when the last touch was the other team", () => {
    const m = createMatch({ mode: "cpu", difficulty: "normal", seed: 5 });
    m.lastTouch = { team: "left", name: "Chispa" };
    m.ball.x = WORLD.mouth - 18;
    m.ball.y = MID_GOAL;
    checkGoal(m);
    assert.equal(m.ownGoal, true);
    assert.equal(m.banner, "¡AUTOGOL!");
  });
});

describe("resolveArena (elevated goals)", () => {
  it("bounces the ball off the solid wall below the lower lip", () => {
    const b = { x: WORLD.mouth + 8, y: WORLD.goalBottom + 70, vx: -1100, vy: 0, hw: 16, hh: 16 };
    const hit = resolveArena(b, 0.86, 0.64);
    assert.equal(hit.bonk, true);
    assert.ok(b.vx > 0, `vx should flip positive, got ${b.vx}`);
    assert.ok(b.x >= WORLD.mouth + 16, `ball must stay outside the goal, got ${b.x}`);
  });

  it("bounces off the upper round post (larguero)", () => {
    const b = { x: WORLD.mouth - 21, y: WORLD.goalTop + 21, vx: 420, vy: -300, hw: 16, hh: 16 };
    const hit = resolveArena(b, 0.86, 0.64);
    assert.equal(hit.bonk, true);
    assert.ok(b.vx < 0, `top-post rebound should send the ball back, got ${b.vx}`);
    assert.ok(b.vy > 0, `top-post rebound should push down, got ${b.vy}`);
  });

  it("bounces off the lower round post (borde inferior)", () => {
    const b = { x: WORLD.mouth - 21, y: WORLD.goalBottom - 21, vx: 420, vy: 300, hw: 16, hh: 16 };
    const hit = resolveArena(b, 0.86, 0.64);
    assert.equal(hit.bonk, true);
    assert.ok(b.vx < 0, `bottom-post rebound should send the ball back, got ${b.vx}`);
    assert.ok(b.vy < 0, `bottom-post rebound should push up, got ${b.vy}`);
  });

  it("lets the ball cross the centre of the opening without a wall stop", () => {
    const b = { x: WORLD.mouth - 5, y: MID_GOAL, vx: -800, vy: 0, hw: 16, hh: 16 };
    const hit = resolveArena(b, 0.86, 0.64);
    assert.equal(hit.bonk, false);
    assert.equal(b.vx, -800);
    assert.ok(b.x < WORLD.mouth, "ball should be inside the pocket");
  });

  it("cannot tunnel through the lower wall at 1100 px/s and STEP=1/120", () => {
    const b = { x: WORLD.mouth + 120, y: WORLD.goalBottom + 85, vx: -1100, vy: 0, hw: 16, hh: 16 };
    let bonked = false;
    for (let i = 0; i < 60; i++) {
      b.x += b.vx * STEP;
      const hit = resolveArena(b, 0.86, 0.64);
      bonked ||= hit.bonk;
    }
    assert.equal(bonked, true);
    assert.ok(b.vx > 0, `ball should rebound, got ${b.vx}`);
    assert.ok(b.x >= WORLD.mouth + 16 - 0.01, `ball tunneled into goal: ${b.x}`);
  });

  it("keeps fighters out of the goal mouth even in mid-air", () => {
    const b = { x: WORLD.mouth - 10, y: MID_GOAL, vx: -300, vy: 0, hw: PLAYER.hw, hh: PLAYER.hh };
    resolveArena(b, 0.1, 0, { fighter: true });
    assert.ok(b.x >= WORLD.mouth + PLAYER.hw - 0.01, `fighter entered goal: ${b.x}`);
    assert.ok(b.vx > 0);
  });

  it("rests a body on the ground and bounces it off the ceiling", () => {
    const floor = { x: 500, y: 510, vx: 0, vy: 100, hw: 16, hh: 16 };
    const fh = resolveArena(floor, 0.86, 0);
    assert.equal(fh.ground, true);
    assert.equal(floor.y, WORLD.ground - 16);
    assert.equal(floor.vy, 0);

    const ceil = { x: 500, y: 40, vx: 0, vy: -100, hw: 16, hh: 16 };
    const ch = resolveArena(ceil, 0.86, 0);
    assert.equal(ch.bonk, true);
    assert.equal(ceil.y, WORLD.ceil + 16);
    assert.ok(ceil.vy > 0);
  });
});

describe("bot defense", () => {
  it("jumps, strikes and prevents at least some shots aimed at its elevated goal", () => {
    let prevented = 0;
    let jumped = 0;
    let doubleJumped = 0;
    let struck = 0;
    for (const seed of [1, 2, 3, 4, 5, 6, 7, 8]) {
      const m = createMatch({ mode: "cpu", difficulty: "normal", seed });
      const bot = m.fighters.find((f) => f.team === "right");
      assert.ok(bot);
      // Give the single bot a readable emergency: ball flying toward its
      // window from midfield. The human stays idle.
      bot.x = WORLD.w - WORLD.mouth - 125;
      bot.y = WORLD.ground - PLAYER.hh;
      m.ball.x = WORLD.w - WORLD.mouth - 230;
      m.ball.y = MID_GOAL + 25;
      m.ball.vx = 720;
      m.ball.vy = -80;
      let sawAir = false;
      let sawDouble = false;
      let sawStrike = false;
      for (let i = 0; i < 200; i++) {
        stepMatch(m, PADS, STEP);
        if (!bot.grounded) sawAir = true;
        if (!bot.grounded && bot.jumpsLeft === 0) sawDouble = true;
        if (bot.atk === "startup" || bot.atk === "active") sawStrike = true;
      }
      if (m.scoreL === 0) prevented++;
      if (sawAir) jumped++;
      if (sawDouble) doubleJumped++;
      if (sawStrike) struck++;
    }
    assert.ok(prevented >= 5, `bot should prevent some of 8 attempts, got ${prevented}`);
    assert.ok(jumped >= 5, `bot should jump to defend, got ${jumped} attempts`);
    assert.ok(doubleJumped >= 2, `bot should use the second jump, got ${doubleJumped} attempts`);
    assert.ok(struck >= 4, `bot should strike to clear, got ${struck} attempts`);
  });

  it("el bot también ataca y puede marcar", () => {
    let goals = 0;
    for (const seed of [1, 2, 3, 4, 5, 6]) {
      const m = createMatch({ mode: "cpu", difficulty: "hard", seed });
      for (let i = 0; i < 120 * 45 && m.phase !== "over"; i++) {
        stepMatch(m, PADS, STEP);
      }
      goals += m.scoreR;
    }
    assert.ok(goals > 0, `bot should score at least once, got ${goals}`);
  });
});

describe("gol de oro (muerte súbita)", () => {
  it("empate a 0:00 → muerte súbita: el partido sigue y el reloj se congela", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 41 });
    m.kickoffGrace = 0;
    m.scoreL = 1;
    m.scoreR = 1;
    m.time = 0.05;
    m.ball.vx = 0;
    m.ball.vy = 0;
    m.ball.flame = 0;
    step(m, 30); // 0.25 s: el reloj llega a 0
    assert.equal(m.sudden, true, "tied at 0:00 must enter sudden death");
    assert.equal(m.phase, "play", "match must continue in sudden death");
    assert.equal(m.time, 0);
    step(m, 120); // 1 s más: el reloj no avanza en muerte súbita
    assert.equal(m.time, 0, "clock stays frozen during sudden death");
    assert.equal(m.phase, "play");
  });

  it("el gol de oro gana el partido: tras la celebración, phase over con ganador", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 42 });
    m.kickoffGrace = 0;
    m.scoreL = 2;
    m.scoreR = 2;
    m.time = 0.05;
    m.ball.vx = 0;
    m.ball.vy = 0;
    m.ball.flame = 0;
    step(m, 30);
    assert.equal(m.sudden, true);
    // Gol de oro de la izquierda en la portería derecha.
    m.ball.x = WORLD.w - 40;
    m.ball.y = (WORLD.goalTop + WORLD.goalBottom) / 2;
    m.ball.vx = 500;
    m.ball.vy = 0;
    checkGoal(m);
    assert.equal(m.phase, "goal");
    assert.equal(m.pendingOver, true, "goal in sudden death must end the match");
    step(m, Math.ceil(2 / STEP)); // celebración 1.7 s
    assert.equal(m.phase, "over");
    assert.equal(m.scoreL, 3);
    assert.equal(m.scoreR, 2);
    assert.notEqual(m.scoreL, m.scoreR, "sudden death always produces a winner");
  });

  it("sin empate a 0:00 el partido termina normal (sin muerte súbita)", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 43 });
    m.kickoffGrace = 0;
    m.scoreL = 2;
    m.scoreR = 1;
    m.time = 0.05;
    m.ball.vx = 0;
    m.ball.vy = 0;
    m.ball.flame = 0;
    step(m, 30);
    assert.equal(m.sudden, false);
    assert.equal(m.phase, "over");
  });
});

describe("player-ball collision by body part", () => {
  function setup() {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 17 });
    m.kickoffGrace = 0;
    const p = m.fighters[0];
    p.x = 400; p.y = WORLD.ground - PLAYER.hh; p.vx = 0; p.vy = 0;
    p.grounded = true; p.facing = 1; p.atk = "idle"; p.touchCd = 0; p.hitBall = false;
    const q = m.fighters[1];
    q.x = 950; q.y = WORLD.ground - PLAYER.hh;
    return { m, p };
  }

  it("head: ball bounces off the drawn head, not 13 px inside it", () => {
    const { m, p } = setup();
    m.ball.x = p.x; m.ball.y = p.y - 160; m.ball.vx = 0; m.ball.vy = 0;
    let deepest = m.ball.y;
    for (let i = 0; i < 120 && m.ball.vy >= 0; i++) {
      step(m, 1);
      deepest = Math.max(deepest, m.ball.y);
    }
    assert.ok(m.ball.vy < 0, "ball should bounce up off the head");
    // Head top is at p.y - 41; the ball centre must never get past p.y - 54.
    assert.ok(deepest <= p.y - 54, `ball sank to ${deepest}, head top is ${p.y - 41}`);
  });

  it("chest: ball reacts at the visual chest (34 px), not 10 px early", () => {
    const { m, p } = setup();
    m.ball.x = p.x - 50; m.ball.y = p.y; m.ball.vx = 200; m.ball.vy = 0;
    let minDx = Infinity;
    for (let i = 0; i < 60 && m.ball.vx > 0; i++) {
      step(m, 1);
      minDx = Math.min(minDx, Math.abs(m.ball.x - p.x));
    }
    assert.ok(m.ball.vx < 0, "ball should bounce back off the chest");
    assert.ok(minDx >= 33, `ball got to ${minDx} px from the chest centre`);
  });

  it("punch: a ball behind the player is not grabbed", () => {
    const { m, p } = setup();
    p.atk = "active"; p.atkT = 0; p.atkPower = "normal"; p.hitBall = false; p.didLunge = true;
    m.ball.x = p.x - 45; m.ball.y = p.y - 20; m.ball.vx = 0; m.ball.vy = 0;
    step(m, 1);
    assert.equal(m.ball.vx, 0);
  });

  it("punch: a ball in front still launches", () => {
    const { m, p } = setup();
    p.atk = "active"; p.atkT = 0; p.atkPower = "normal"; p.hitBall = false; p.didLunge = true;
    m.ball.x = p.x + 45; m.ball.y = p.y - 20; m.ball.vx = 0; m.ball.vy = 0;
    step(m, 1);
    assert.ok(m.ball.vx > 400, `punch should launch the ball, got vx=${m.ball.vx}`);
  });

  it("punch: keeps part of a fast incoming ball", () => {
    const { m, p } = setup();
    p.atk = "active"; p.atkT = 0; p.atkPower = "normal"; p.hitBall = false; p.didLunge = true;
    m.ball.x = p.x + 40; m.ball.y = p.y - 20; m.ball.vx = 400; m.ball.vy = 0;
    step(m, 1);
    // Base punch is 566; a ball already flying at 400 must leave faster.
    assert.ok(m.ball.vx > 600, `punch should exceed base 566, got ${m.ball.vx}`);
  });

  it("header: a fast falling ball leaves faster than the base 860", () => {
    const { m, p } = setup();
    p.y = 300; p.vy = 0; p.grounded = false;
    m.ball.x = p.x; m.ball.y = p.y - 90; m.ball.vx = 0; m.ball.vy = 300;
    let fired = false;
    for (let i = 0; i < 200; i++) {
      step(m, 1);
      if (Math.hypot(m.ball.vx, m.ball.vy) > 900) { fired = true; break; }
    }
    assert.ok(fired, "header should fire above base speed");
  });

  it("feet: a rolling ball bounces back cleanly, without popping up", () => {
    const { m, p } = setup();
    m.ball.x = p.x - 60; m.ball.y = WORLD.ground - 16; m.ball.vx = 300; m.ball.vy = 0;
    for (let i = 0; i < 60 && m.ball.vx > 0; i++) step(m, 1);
    assert.ok(m.ball.vx < 0, "ball should bounce back off the feet");
    assert.ok(Math.abs(m.ball.vy) < 30, `ball should not pop up, vy=${m.ball.vy}`);
  });
});

describe("goal celebration (ball enters the net)", () => {
  function scoredRight(m: Match) {
    // Ball flying into the right goal, like a real shot.
    m.ball.x = WORLD.w - WORLD.mouth - 40;
    m.ball.y = MID_GOAL;
    m.ball.vx = 850;
    m.ball.vy = 0;
    step(m, 12);
    assert.equal(m.phase, "goal");
    assert.equal(m.scoreL, 1);
  }

  it("lets the ball fly into the pocket instead of freezing it at the line", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 9 });
    scoredRight(m);
    step(m, 20);
    assert.ok(m.ball.x > WORLD.w - WORLD.mouth + 20, `ball must be deep inside the pocket, got ${m.ball.x}`);
    assert.ok(
      m.ball.x <= WORLD.w - WORLD.back - WORLD.ballR + 1,
      `ball must not cross the back net, got ${m.ball.x}`,
    );
    assert.ok(
      Math.hypot(m.ball.vx, m.ball.vy) < 400,
      `the net must slow the ball down, got ${Math.hypot(m.ball.vx, m.ball.vy)}`,
    );
  });

  it("catches the ball in the net: it settles inside the pocket before kickoff", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 9 });
    scoredRight(m);
    step(m, 150);
    assert.equal(m.phase, "goal");
    assert.ok(m.ball.x > WORLD.w - WORLD.mouth, `ball must stay in the pocket, got ${m.ball.x}`);
    assert.ok(
      m.ball.x <= WORLD.w - WORLD.back - WORLD.ballR + 1,
      `ball must stay in the pocket, got ${m.ball.x}`,
    );
    assert.ok(
      Math.hypot(m.ball.vx, m.ball.vy) < 120,
      `ball must be nearly stopped, got ${Math.hypot(m.ball.vx, m.ball.vy)}`,
    );
  });

  it("re-pulses the camera shake when the ball hits the back of the net", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 9 });
    scoredRight(m);
    m.shake = 0.2;
    step(m, 12);
    assert.ok(m.shake >= 0.9, `shake must pulse on the net impact, got ${m.shake}`);
  });

  it("bursts 72 confetti + 24 sparks on a goal", () => {
    const m = createMatch({ mode: "cpu", difficulty: "normal", seed: 5 });
    m.ball.x = WORLD.mouth - 18;
    m.ball.y = MID_GOAL;
    checkGoal(m);
    assert.ok(m.particles.length >= 90, `expected a big burst, got ${m.particles.length}`);
  });

  it("stays deterministic through the whole goal celebration", () => {
    const run = () => {
      const m = createMatch({ mode: "online", difficulty: "normal", seed: 33 });
      m.ball.x = WORLD.w - WORLD.mouth - 40;
      m.ball.y = MID_GOAL;
      m.ball.vx = 850;
      m.ball.vy = 0;
      step(m, 180);
      return snapshot(m);
    };
    assert.equal(run(), run());
  });
});

describe("crowdDanger (tribuna dinámica)", () => {
  it("is quiet at kickoff, in the middle of the pitch", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 5 });
    const d = crowdDanger(m);
    assert.ok(d < 0.2, `kickoff should be quiet, got ${d}`);
  });

  it("rises as the ball approaches a goal", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 5 });
    m.ball.x = WORLD.w - 300;
    m.ball.y = MID_GOAL;
    m.ball.vx = 0;
    m.ball.vy = 0;
    const mid = crowdDanger(m);
    m.ball.x = WORLD.w - WORLD.mouth - 20;
    const near = crowdDanger(m);
    assert.ok(near > mid, `near the goal (${near}) must be louder than midfield (${mid})`);
    assert.ok(near > 0.8, `at the mouth it must be nearly max, got ${near}`);
  });

  it("is max inside the goal mouth", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 5 });
    m.ball.x = WORLD.w - WORLD.mouth;
    m.ball.y = MID_GOAL;
    m.ball.vx = 0;
    m.ball.vy = 0;
    assert.equal(crowdDanger(m), 1);
  });

  it("rewards a fast ball flying toward the goal", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 5 });
    m.ball.x = WORLD.w - 400;
    m.ball.y = MID_GOAL;
    m.ball.vx = 0;
    m.ball.vy = 0;
    const still = crowdDanger(m);
    m.ball.vx = 900;
    const flying = crowdDanger(m);
    assert.ok(flying > still, `a shot toward the goal (${flying}) must be louder than a still ball (${still})`);
  });

  it("stays in 0..1 for any ball position", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 5 });
    for (const [x, y, vx] of [
      [0, 0, 0],
      [1040, 580, -1350],
      [520, 200, 1350],
      [82, 330, 0],
    ] as const) {
      m.ball.x = x;
      m.ball.y = y;
      m.ball.vx = vx;
      m.ball.vy = 0;
      const d = crowdDanger(m);
      assert.ok(d >= 0 && d <= 1, `danger out of range at (${x},${y}): ${d}`);
    }
  });
});

describe("power-up de la burbuja (disco morado)", () => {
  it("la burbuja no aparece antes de los 6 s", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 21 });
    assert.equal(m.bubble, null);
    step(m, Math.floor(5 / STEP));
    assert.equal(m.bubble, null, "no bubble before 6 s");
  });

  it("la burbuja aparece a los ~6 s en la zona central y a altura alcanzable", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 21 });
    step(m, Math.ceil(6.5 / STEP));
    assert.ok(m.bubble, "bubble should have spawned by 6.5 s");
    const b = m.bubble;
    assert.ok(b.x >= 380 && b.x <= 660, `bubble x out of range: ${b.x}`);
    assert.ok(b.y >= 280 && b.y <= 380, `bubble y out of range: ${b.y}`);
    assert.equal(b.r, POWERUP.bubbleR);
  });

  it("misma semilla, misma burbuja (spawn determinista)", () => {
    const a = createMatch({ mode: "online", difficulty: "normal", seed: 22 });
    const b = createMatch({ mode: "online", difficulty: "normal", seed: 22 });
    step(a, Math.ceil(9 / STEP));
    step(b, Math.ceil(9 / STEP));
    assert.ok(a.bubble && b.bubble);
    assert.equal(a.bubble!.x, b.bubble!.x);
    assert.equal(a.bubble!.y, b.bubble!.y);
    assert.equal(stateHash(a), stateHash(b));
  });

  it("un golpe revienta la burbuja y suelta el disco", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 23 });
    m.kickoffGrace = 0;
    const f = m.fighters[0];
    // Burbuja a altura de golpe con el luchador en el suelo.
    m.bubble = { x: f.x + 55, y: f.y - 8, r: POWERUP.bubbleR, bobT: 0, ttl: 15 };
    f.facing = 1;
    f.atk = "active";
    f.atkT = 0;
    f.atkPower = "normal";
    step(m, 1);
    assert.equal(m.bubble, null, "bubble should pop on a strike");
    assert.ok(m.item, "the disc item should drop where the bubble was");
    assert.equal(m.item!.r, POWERUP.itemR);
  });

  it("el balón NO revienta la burbuja (solo el golpe)", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 24 });
    m.kickoffGrace = 0;
    m.bubble = { x: 520, y: 300, r: POWERUP.bubbleR, bobT: 0, ttl: 15 };
    m.ball.x = 520;
    m.ball.y = 300;
    m.ball.vx = 0;
    m.ball.vy = 0;
    m.fighters[0].x = 100;
    m.fighters[1].x = 940;
    step(m, 10);
    assert.ok(m.bubble, "ball alone must not pop the bubble");
    assert.equal(m.item, null);
  });

  it("al tocar el disco suelto aparece el escudo en la portería de quien lo coge (10 s)", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 25 });
    m.kickoffGrace = 0;
    const f = m.fighters[0];
    assert.equal(f.team, "left");
    m.item = { x: f.x, y: f.y, r: POWERUP.itemR, ttl: 6 };
    step(m, 1);
    assert.equal(m.item, null, "item should be collected on touch");
    assert.ok(m.shields.left, "shield should activate");
    assert.ok(Math.abs(m.shields.left!.t - POWERUP.shieldSecs) < 0.05, `shield t: ${m.shields.left!.t}`);
    assert.equal(m.shields.right, null, "the rival gets no shield");
    const d = shieldDiscFor(m, "left");
    assert.ok(d, "disc position should exist");
    assert.equal(d!.x, WORLD.mouth, "disc sits in the left goal mouth");
    assert.equal(d!.r, POWERUP.discR);
  });

  it("el disco oscila verticalmente dentro de la portería sin tocar los discos de los postes", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 26 });
    m.shields.right = { t: POWERUP.shieldSecs };
    const ys: number[] = [];
    for (let i = 0; i < 400; i++) {
      const d = shieldDiscFor(m, "right");
      assert.ok(d);
      ys.push(d!.y);
      m.shields.right!.t -= STEP;
    }
    const lo = Math.min(...ys);
    const hi = Math.max(...ys);
    const center = (WORLD.goalTop + WORLD.goalBottom) / 2;
    assert.ok(lo >= WORLD.goalTop + POWERUP.discR - 1, `disc top ${lo} above goalTop`);
    assert.ok(hi <= WORLD.goalBottom - POWERUP.discR + 1, `disc bottom ${hi} below goalBottom`);
    assert.ok(hi - lo > 50, `disc should sweep the goal mouth, swept ${hi - lo}`);
    assert.ok(Math.abs((lo + hi) / 2 - center) < 5, "disc oscillates around the goal centre");
    // Sin solape con los discos esquineros de los postes: al menos 1 px de aire.
    assert.ok(
      lo - POWERUP.discR >= WORLD.goalTop + WORLD.postR + 1,
      `disc overlaps the top post disc (top edge ${lo - POWERUP.discR})`,
    );
    assert.ok(
      hi + POWERUP.discR <= WORLD.goalBottom - WORLD.postR - 1,
      `disc overlaps the bottom post disc (bottom edge ${hi + POWERUP.discR})`,
    );
  });

  it("el balón rebota en el disco y NO entra en la portería por ahí", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 27 });
    m.kickoffGrace = 0;
    m.fighters[0].x = 100;
    m.fighters[1].x = 940;
    m.shields.left = { t: POWERUP.shieldSecs };
    // Tiro recto a la portería izquierda, a la altura del disco (centro).
    m.ball.x = 220;
    m.ball.y = (WORLD.goalTop + WORLD.goalBottom) / 2;
    m.ball.vx = -800;
    m.ball.vy = 0;
    step(m, 60);
    assert.equal(m.scoreR, 0, "ball must not score through the disc (left goal = right scores)");
    assert.equal(m.phase, "play");
    assert.ok(m.ball.vx > 0, `ball should bounce back off the disc, vx=${m.ball.vx}`);
  });

  it("el balón SÍ puede entrar por encima/debajo del disco (no es un muro)", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 28 });
    m.kickoffGrace = 0;
    m.fighters[0].x = 100;
    m.fighters[1].x = 940;
    m.shields.left = { t: POWERUP.shieldSecs };
    // Tiro pegado al larguero, lejos del disco (que está en el centro).
    m.ball.x = 220;
    m.ball.y = WORLD.goalTop + 20;
    m.ball.vx = -800;
    m.ball.vy = 0;
    step(m, 60);
    assert.equal(m.scoreR, 1, "ball should score going around the disc (left goal = right scores)");
    assert.equal(m.phase, "goal");
  });

  it("el escudo se agota a los 10 segundos", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 29 });
    m.shields.left = { t: POWERUP.shieldSecs };
    step(m, Math.ceil(9.9 / STEP));
    assert.ok(m.shields.left, "shield should still be up at 9.9 s");
    step(m, Math.ceil(0.2 / STEP));
    assert.equal(m.shields.left, null, "shield should expire at 10 s");
    assert.equal(shieldDiscFor(m, "left"), null);
  });

  it("al marcar gol el power-up persiste entero (burbuja, ítem y escudos)", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 30 });
    m.kickoffGrace = 0;
    m.bubble = { x: 520, y: 300, r: POWERUP.bubbleR, bobT: 0, ttl: 12 };
    m.item = { x: 300, y: 300, r: POWERUP.itemR, ttl: 6 };
    m.shields.left = { t: 5 };
    m.shields.right = { t: 8 };
    m.ball.x = WORLD.w - 40;
    m.ball.y = (WORLD.goalTop + WORLD.goalBottom) / 2;
    m.ball.vx = 500;
    m.ball.vy = 0;
    checkGoal(m);
    assert.equal(m.phase, "goal");
    assert.ok(m.bubble, "bubble must survive the goal");
    assert.equal(m.bubble!.x, 520, "bubble keeps its position");
    assert.equal(m.bubble!.y, 300);
    assert.equal(m.bubble!.ttl, 12, "bubble keeps its remaining time");
    assert.ok(m.item, "loose item must survive the goal");
    assert.equal(m.item!.ttl, 6, "item keeps its remaining time");
    assert.ok(m.shields.left, "left shield must survive the goal");
    assert.equal(m.shields.left!.t, 5);
    assert.ok(m.shields.right, "right shield must survive the goal");
    assert.equal(m.shields.right!.t, 8);
  });

  it("el power-up persiste tras el saque y sigue contando su duración", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 36 });
    m.kickoffGrace = 0;
    m.bubble = { x: 520, y: 300, r: POWERUP.bubbleR, bobT: 0, ttl: 12 };
    m.item = { x: 300, y: 300, r: POWERUP.itemR, ttl: 6 };
    m.shields.left = { t: 5 };
    m.shields.right = { t: 8 };
    m.ball.x = WORLD.w - 40;
    m.ball.y = (WORLD.goalTop + WORLD.goalBottom) / 2;
    m.ball.vx = 500;
    m.ball.vy = 0;
    checkGoal(m);
    // 1.7 s de celebración (el power-up no cuenta ahí) + 0.3 s de juego.
    step(m, Math.ceil(2 / STEP));
    assert.equal(m.phase, "play", "kickoff should have happened");
    assert.ok(m.bubble, "bubble must survive the kickoff too");
    assert.ok(
      m.bubble!.ttl > 11.5 && m.bubble!.ttl < 11.9,
      `bubble ttl should be ~11.7 s after the restart, got ${m.bubble!.ttl}`,
    );
    assert.ok(m.item, "item must survive the kickoff too");
    assert.ok(
      m.item!.ttl > 5.5 && m.item!.ttl < 5.9,
      `item ttl should be ~5.7 s after the restart, got ${m.item!.ttl}`,
    );
    assert.ok(m.shields.left && m.shields.right, "shields must survive the kickoff too");
    assert.ok(Math.abs(m.shields.left!.t - 4.7) < 0.1, `left shield t: ${m.shields.left!.t}`);
    assert.ok(Math.abs(m.shields.right!.t - 7.7) < 0.1, `right shield t: ${m.shields.right!.t}`);
    // Y todo se agota solo con su duración, sin que el gol lo haya tocado.
    step(m, Math.ceil(12 / STEP));
    assert.equal(m.bubble, null, "bubble should expire on its own time");
    assert.equal(m.item, null, "item should expire on its own time");
    assert.equal(m.shields.left, null, "left shield should expire on its own time");
    assert.equal(m.shields.right, null, "right shield should expire on its own time");
  });

  it("el hash de sincronía cambia con el power-up (online no se desincroniza en silencio)", () => {
    const a = createMatch({ mode: "online", difficulty: "normal", seed: 31 });
    const b = createMatch({ mode: "online", difficulty: "normal", seed: 31 });
    step(a, Math.ceil(9 / STEP));
    step(b, Math.ceil(9 / STEP));
    assert.equal(stateHash(a), stateHash(b), "same seed must hash equal with a bubble up");
    // Divergir solo un escudo debe cambiar el hash.
    b.shields.left = { t: 7 };
    assert.notEqual(stateHash(a), stateHash(b), "left shield divergence must change the hash");
    b.shields.left = null;
    b.shields.right = { t: 7 };
    assert.notEqual(stateHash(a), stateHash(b), "right shield divergence must change the hash");
  });

  it("el rival puede tener su escudo sin reemplazar el mío (duraciones independientes)", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 32 });
    m.kickoffGrace = 0;
    // Yo ya tengo escudo con 5 s restantes.
    m.shields.left = { t: 5 };
    // El rival coge el disco suelto.
    const f = m.fighters[1];
    assert.equal(f.team, "right");
    m.item = { x: f.x, y: f.y, r: POWERUP.itemR, ttl: 6 };
    step(m, 1);
    assert.ok(m.shields.right, "rival shield should activate");
    assert.ok(Math.abs(m.shields.right!.t - POWERUP.shieldSecs) < 0.05, `rival shield t: ${m.shields.right!.t}`);
    assert.ok(m.shields.left, "my shield must survive the rival pickup");
    assert.ok(Math.abs(m.shields.left!.t - 5) < 0.05, `my shield t must keep counting, not reset: ${m.shields.left!.t}`);
    // Los dos discos defienden a la vez, cada uno en su portería.
    const discs = shieldDiscs(m);
    assert.equal(discs.length, 2, "both discs should be up");
    assert.equal(discs.find((d) => d.team === "left")!.x, WORLD.mouth);
    assert.equal(discs.find((d) => d.team === "right")!.x, WORLD.w - WORLD.mouth);
  });

  it("coger otra burbuja con escudo activo reinicia la duración a 10 s (no se suma)", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 33 });
    m.kickoffGrace = 0;
    m.shields.left = { t: 3 };
    const f = m.fighters[0];
    m.item = { x: f.x, y: f.y, r: POWERUP.itemR, ttl: 6 };
    step(m, 1);
    assert.ok(Math.abs(m.shields.left!.t - POWERUP.shieldSecs) < 0.05, `shield must restart at 10 s, got ${m.shields.left!.t}`);
  });

  it("la segunda burbuja llega entre 7 y 11 s después de que se va la primera", () => {
    const m = createMatch({ mode: "online", difficulty: "normal", seed: 34 });
    step(m, Math.ceil(6.5 / STEP));
    assert.ok(m.bubble, "first bubble should be up");
    // Que la primera desaparezca sola.
    m.bubble!.ttl = 0.01;
    step(m, 2);
    assert.equal(m.bubble, null, "first bubble should be gone");
    // Medir hasta la segunda.
    let waited = 0;
    while (!m.bubble && waited < Math.ceil(12 / STEP)) {
      step(m, 1);
      waited++;
    }
    assert.ok(m.bubble, "second bubble should arrive");
    const secs = waited * STEP;
    assert.ok(secs >= 7 && secs <= 11.5, `second bubble after ${secs.toFixed(2)} s, expected 7-11 s`);
  });
});
