import { describe, it } from "node:test";
import assert from "node:assert/strict";
import { frameOf, CAMERA_MARGIN, type Camera } from "./draw.ts";
import { createMatch, type Match } from "./engine.ts";
import { PLAYER, WORLD } from "./constants.ts";

const PHONE = { w: 390, h: 780 };

function prepare(): Match {
  const m = createMatch({ mode: "online", difficulty: "normal", seed: 31 });
  m.fighters[0].x = 230;
  m.fighters[0].y = WORLD.ground - PLAYER.hh;
  m.fighters[1].x = 810;
  m.fighters[1].y = WORLD.ground - PLAYER.hh;
  m.ball.vx = 0;
  m.ball.vy = 0;
  return m;
}

function assertWorldBounds(cam: Camera) {
  assert.ok(cam.x >= 0, `camera x below world: ${cam.x}`);
  assert.ok(cam.y >= 0, `camera y below world: ${cam.y}`);
  assert.ok(cam.x + cam.w <= WORLD.w + 0.001, `camera right edge outside world: ${cam.x + cam.w}`);
  assert.ok(cam.y + cam.h <= WORLD.h + 0.001, `camera bottom edge outside world: ${cam.y + cam.h}`);
}

function assertActionInside(cam: Camera, m: Match) {
  const human = m.fighters[0];
  assert.ok(human.x >= cam.x && human.x <= cam.x + cam.w, `human outside camera: ${human.x}`);
  assert.ok(m.ball.x >= cam.x && m.ball.x <= cam.x + cam.w, `ball outside camera x: ${m.ball.x}`);
  assert.ok(m.ball.y >= cam.y && m.ball.y <= cam.y + cam.h, `ball outside camera y: ${m.ball.y}`);
}

describe("frameOf vertical camera", () => {
  it("uses the current close zoom when the human and ball are together", () => {
    const m = prepare();
    m.ball.x = 250;
    m.ball.y = 470;
    const cam = frameOf(PHONE.w, PHONE.h, m, 240, 1 / 60);
    const minViewW = Math.min(WORLD.w, WORLD.h * (PHONE.w / PHONE.h));
    assert.ok(Math.abs(cam.w - minViewW) < 0.01, `expected ${minViewW}, got ${cam.w}`);
    assert.equal(cam.y, 0);
    assert.equal(cam.h, WORLD.h);
    assertActionInside(cam, m);
    assertWorldBounds(cam);
  });

  it("zooms out toward the far ball and keeps both actors inside", () => {
    const m = prepare();
    m.ball.x = 900;
    m.ball.y = 250;
    const minViewW = Math.min(WORLD.w, WORLD.h * (PHONE.w / PHONE.h));
    const cam = frameOf(PHONE.w, PHONE.h, m, 650, 1 / 60);
    assert.ok(cam.w > minViewW, `camera should zoom out: ${cam.w}`);
    assert.ok(cam.w <= WORLD.w, `camera exceeded world width: ${cam.w}`);
    assertActionInside(cam, m);
    assertWorldBounds(cam);
    assert.ok(m.fighters[0].x - cam.x >= CAMERA_MARGIN - 0.5);
    assert.ok(cam.x + cam.w - m.ball.x >= CAMERA_MARGIN - 0.5);
  });

  it("keeps high balls inside the vertical frame", () => {
    const m = prepare();
    m.ball.x = 280;
    m.ball.y = WORLD.ceil + WORLD.ballR;
    const cam = frameOf(PHONE.w, PHONE.h, m, 250, 1 / 60);
    assert.ok(m.ball.y >= cam.y && m.ball.y <= cam.y + cam.h);
    assertActionInside(cam, m);
    assertWorldBounds(cam);
  });

  it("never leaves the world even with extreme actors", () => {
    const m = prepare();
    m.fighters[0].x = 20;
    m.ball.x = 1025;
    m.ball.y = 40;
    m.ball.vx = 1100;
    const cam = frameOf(360, 640, m, 520, 1 / 60);
    assertWorldBounds(cam);
    assertActionInside(cam, m);
    assert.ok(cam.w <= WORLD.w);
  });

  it("zooms back in smoothly after the ball returns", () => {
    const m = prepare();
    m.ball.x = 990;
    m.ball.y = 250;
    let cam = frameOf(PHONE.w, PHONE.h, m, 650, 1 / 60);
    const wide = cam.w;
    m.ball.x = 250;
    m.ball.y = 470;
    const deltas: number[] = [];
    for (let i = 0; i < 40; i++) {
      const before = m.camViewW;
      cam = frameOf(PHONE.w, PHONE.h, m, 240, 1 / 60);
      deltas.push(before - m.camViewW);
    }
    const minViewW = Math.min(WORLD.w, WORLD.h * (PHONE.w / PHONE.h));
    assert.ok(cam.w < wide, `camera should come back in: ${cam.w} < ${wide}`);
    assert.ok(cam.w >= minViewW);
    assert.ok(deltas.some((d) => d > 0), "zoom-in should be animated, not instant");
    assertActionInside(cam, m);
    assertWorldBounds(cam);
  });

  it("anticipates ball velocity horizontally", () => {
    const still = prepare();
    still.fighters[1].x = 1000;
    still.ball.x = 500;
    still.ball.y = 360;
    const camStill = frameOf(PHONE.w, PHONE.h, still, 420, 1 / 60);
    const centerStill = camStill.x + camStill.w / 2;

    const moving = prepare();
    moving.fighters[1].x = 1000;
    moving.ball.x = 500;
    moving.ball.y = 360;
    moving.ball.vx = 900;
    const camMoving = frameOf(PHONE.w, PHONE.h, moving, 420, 1 / 60);
    const centerMoving = camMoving.x + camMoving.w / 2;
    assert.ok(camMoving.w >= camStill.w, "look-ahead must not crop the flight path");
    assert.ok(centerMoving > centerStill, `look-ahead should shift view right: ${centerMoving} > ${centerStill}`);
  });

  it("reuses the Camera object and leaves horizontal framing untouched", () => {
    const m = prepare();
    m.ball.x = 980;
    const first = frameOf(390, 780, m, 500, 1 / 60);
    const second = frameOf(390, 780, m, 500, 1 / 60);
    assert.equal(first, second, "vertical camera must be the reused CAMERA object");

    const wide = frameOf(1280, 720, m, 500, 1 / 60);
    const scale = Math.min(1280 / WORLD.w, 720 / WORLD.h);
    assert.equal(wide.x, 0);
    assert.equal(wide.y, 0);
    assert.equal(wide.w, WORLD.w);
    assert.equal(wide.h, WORLD.h);
    assert.ok(Math.abs(wide.scale - scale) < 1e-9);
    assert.ok(Math.abs(wide.ox - (1280 - WORLD.w * scale) / 2) < 1e-9);
    assert.ok(Math.abs(wide.oy - (720 - WORLD.h * scale) / 2) < 1e-9);
  });

  it("follows p1 when focusControl is p1 (the guest in online)", () => {
    const m = prepare();
    // p1 lejos a la derecha; p0 y la pelota a la izquierda.
    m.fighters[1].x = 900;
    m.fighters[1].y = WORLD.ground - PLAYER.hh;
    m.fighters[0].x = 150;
    m.ball.x = 180;
    m.ball.y = 470;
    const camGuest = frameOf(PHONE.w, PHONE.h, m, 850, 1 / 60, "p1");
    const p1 = m.fighters[1];
    assert.ok(p1.x >= camGuest.x && p1.x <= camGuest.x + camGuest.w, `p1 outside camera: ${p1.x}`);
    assert.ok(m.ball.x >= camGuest.x && m.ball.x <= camGuest.x + camGuest.w, `ball outside camera x: ${m.ball.x}`);
    assertWorldBounds(camGuest);

    // Con el foco por defecto (p0) ese mismo p1 queda fuera de cuadro:
    // el foco es lo que decide a quién sigue la cámara.
    const m2 = prepare();
    m2.fighters[1].x = 900;
    m2.fighters[1].y = WORLD.ground - PLAYER.hh;
    m2.fighters[0].x = 150;
    m2.ball.x = 180;
    m2.ball.y = 470;
    const camHost = frameOf(PHONE.w, PHONE.h, m2, 160, 1 / 60);
    assert.ok(!(p1.x >= camHost.x && p1.x <= camHost.x + camHost.w), "p1 should be outside the p0-focused camera");
    assertWorldBounds(camHost);
  });
});

describe("frameOf continuity at kickoff", () => {
  it("never jumps when the rival runs into the frame as the ball drops", () => {
    const m = prepare();
    m.fighters[0].x = 230;
    m.fighters[1].x = 765;
    m.ball.x = 520;
    m.ball.y = 200;
    let prevX = NaN;
    let prevW = NaN;
    let maxDx = 0;
    let maxDw = 0;
    // 1.5 s a 60 fps: el rival corre hacia la pelota y el balón cae.
    for (let f = 0; f < 90; f++) {
      m.fighters[1].x = Math.max(540, m.fighters[1].x - 5.5);
      m.fighters[0].x = Math.min(480, m.fighters[0].x + 3);
      m.ball.y = Math.min(480, m.ball.y + (f > 20 ? 6 : 0));
      const cam = frameOf(PHONE.w, PHONE.h, m, (m.fighters[0].x + m.ball.x) / 2, 1 / 60);
      if (f > 0) {
        maxDx = Math.max(maxDx, Math.abs(cam.x - prevX));
        maxDw = Math.max(maxDw, Math.abs(cam.w - prevW));
      }
      prevX = cam.x;
      prevW = cam.w;
    }
    assert.ok(maxDx < 6, `la cámara saltó ${maxDx.toFixed(1)} px en un frame`);
    assert.ok(maxDw < 10, `el zoom saltó ${maxDw.toFixed(1)} px en un frame`);
  });
});

describe("frameOf crossing midfield", () => {
  for (const dir of [1, -1]) {
    it(`no jump while the human crosses the middle (${dir > 0 ? "→" : "←"}) with the rival standing far away`, () => {
      const m = prepare();
      m.ball.y = 480;
      m.fighters[1].x = dir > 0 ? 800 : 240;
      let prev = NaN;
      let maxDx = 0;
      for (let f = 0; f < 170; f++) {
        const hx = dir > 0 ? 250 + f * 3.2 : 800 - f * 3.2;
        m.fighters[0].x = hx;
        m.ball.x = hx + dir * 60;
        const cam = frameOf(PHONE.w, PHONE.h, m, hx, 1 / 60);
        if (f > 0) maxDx = Math.max(maxDx, Math.abs(cam.x - prev));
        prev = cam.x;
      }
      assert.ok(maxDx < 12, `la cámara saltó ${maxDx.toFixed(1)} px en un frame`);
    });
  }
});

