/**
 * Run with: node --experimental-strip-types --test src/game/fighter-rig.test.ts
 */
import { describe, it } from "node:test";
import assert from "node:assert/strict";
import { createMatch, attackReach, type Fighter } from "./engine.ts";
import { GROUND_Y, ANKLE_H, poseFor, solveLimb } from "./fighter-rig.ts";
import { CHARACTERS } from "./characters.ts";
import { LOOK_OPTIONS, lookFromCharacter, paletteOf, sanitizeLook } from "./fighter-style.ts";

function fighter(over: Partial<Fighter> = {}): Fighter {
  const m = createMatch({ mode: "demo", difficulty: "normal", seed: 3 });
  return Object.assign(m.fighters[0], { x: 0, y: 0, vx: 0, vy: 0, grounded: true, atk: "idle", atkT: 0, stun: 0, charge: 0 }, over);
}

const sole = (end: { y: number }) => end.y + ANKLE_H;

describe("fighter rig", () => {
  it("two-bone IK reaches the target and bends the joint to the requested side", () => {
    const l = solveLimb({ x: 0, y: 0 }, { x: 0, y: 14 }, 9.5, 9.5, 1);
    assert.ok(Math.abs(l.end.y - 14) < 1e-6);
    assert.ok(l.joint.x > 0, "rodilla hacia delante");
    const a = solveLimb({ x: 0, y: 0 }, { x: 0, y: 12 }, 7.5, 7, -1);
    assert.ok(a.joint.x < 0, "codo hacia atrás");
  });

  it("idle and every run frame keep a foot planted exactly on the ground", () => {
    for (let i = 0; i < 24; i++) {
      const f = fighter({ vx: i === 0 ? 0 : 300, anim: i * 0.04 });
      const p = poseFor(f, i * 0.1, "play", attackReach(f));
      const low = Math.max(sole(p.legB.end), sole(p.legF.end));
      assert.ok(Math.abs(low - GROUND_Y) < 0.01, `frame ${i}: pie más bajo en ${low}`);
      assert.ok(sole(p.legB.end) <= GROUND_Y + 0.01 && sole(p.legF.end) <= GROUND_Y + 0.01, "nunca atraviesa el suelo");
    }
  });

  it("the run cycle actually moves the legs and swings the arms", () => {
    const xs = new Set<number>();
    for (let i = 0; i < 12; i++) {
      const f = fighter({ vx: 300, anim: i * 0.04 });
      xs.add(Math.round(poseFor(f, 0, "play", 40).legF.end.x));
    }
    assert.ok(xs.size >= 5, "el pie delantero recorre varias posiciones");
  });

  for (const charged of [false, true]) {
    for (const air of [false, true]) {
      it(`${air ? "flying kick" : "ground punch+kick"} (${charged ? "charged" : "normal"}) lands foot and fist inside the real hitbox`, () => {
        const f = fighter({ atk: "active", atkT: 0.08, atkPower: charged ? "charged" : "normal", grounded: !air, vy: air ? -50 : 0 });
        const reach = attackReach(f);
        const w = charged ? 44 : 36;
        const p = poseFor(f, 0, "play", reach);
        // Rotación de la pose (patada voladora) aplicada al pie.
        const rotate = (pt: { x: number; y: number }) => {
          const dx = pt.x - p.pivot.x;
          const dy = pt.y - p.pivot.y;
          const c = Math.cos(p.rot);
          const s = Math.sin(p.rot);
          return { x: p.pivot.x + dx * c - dy * s, y: p.pivot.y + dx * s + dy * c };
        };
        const foot = rotate(p.legF.end);
        assert.ok(foot.x >= reach - w / 2 && foot.x <= reach + w / 2, `pie x=${foot.x.toFixed(1)}`);
        assert.ok(foot.y >= -20 && foot.y <= 16 + 4, `pie y=${foot.y.toFixed(1)}`);
        if (!air) {
          assert.ok(p.armF.end.x >= reach - w / 2 - 2, `puño x=${p.armF.end.x.toFixed(1)}`);
          assert.equal(p.smear, "kick");
        } else {
          assert.equal(p.smear, "flykick");
          assert.ok(p.rot < -0.2, "cuerpo inclinado en la patada voladora");
        }
      });
    }
  }
});

describe("fighter style pattern", () => {
  it("every roster figure maps to a valid, serialisable look", () => {
    for (const ch of CHARACTERS) {
      const look = lookFromCharacter(ch);
      const round = JSON.parse(JSON.stringify(look));
      assert.deepEqual(sanitizeLook(round, look), look);
      assert.ok(LOOK_OPTIONS.pattern.includes(look.kit.pattern));
      const pal = paletteOf(look);
      assert.match(pal.skinShade, /^#[0-9a-f]{6}$/);
    }
  });

  it("sanitizeLook repairs garbage from an editor or storage", () => {
    const base = lookFromCharacter(CHARACTERS[0]);
    const bad = sanitizeLook({ build: "giant", headScale: 9, skin: "red", kit: { number: 400, pattern: "dots" }, face: { eyes: "laser" } }, base);
    assert.equal(bad.build, base.build);
    assert.equal(bad.headScale, 1.15);
    assert.equal(bad.skin, base.skin);
    assert.equal(bad.kit.number, 99);
    assert.equal(bad.kit.pattern, base.kit.pattern);
    assert.equal(bad.face.eyes, base.face.eyes);
    assert.deepEqual(sanitizeLook(null, base), base);
  });
});
