import { BALL, JUMP, KICK, MATCH_SECONDS, PLAYER, POWERUP, WORLD } from "./constants.ts";
import {
  CHARACTERS,
  FX_COLORS,
  getCharacter,
  isCharacterId,
  nextCharacterId,
  type CharacterId,
} from "./characters.ts";
import { createRng, nextRand, randomSeed, type RngState } from "./rng.ts";

export type Team = "left" | "right";
export type Mode = "cpu" | "demo" | "online";
export type Difficulty = "easy" | "normal" | "hard";
export type Phase = "play" | "goal" | "over";
export type MatchCharacters = { left?: CharacterId; right?: CharacterId };

export type InputPad = {
  x: number;
  jump: boolean;
  jumpPressed: boolean;
  jumpReleased: boolean;
  attack: boolean;
  attackPressed: boolean;
  attackReleased: boolean;
  down: boolean;
  downPressed: boolean;
};

export type Pads = { p0: InputPad; p1: InputPad };

export type SfxId =
  | "jump"
  | "doublejump"
  | "land"
  | "swish"
  | "kick"
  | "power"
  | "header"
  | "hit"
  | "bounce"
  | "goal"
  | "whistle"
  | "sudden"
  | "stomp"
  | "ui";

export type SfxEvent = { id: SfxId; pan: number; vol?: number };

export type Attack = "idle" | "startup" | "active" | "recover" | "stomp";

type Mind = {
  wait: number;
  axis: number;
  jumpPulse: number;
  doubleJumpNow: boolean;
  attackPulse: number;
  downPulse: number;
  defend: boolean;
  prevJump: boolean;
  prevAttack: boolean;
  prevDown: boolean;
};

export type Fighter = {
  id: number;
  team: Team;
  control: "p0" | "p1" | "bot";
  name: string;
  character: CharacterId;
  x: number;
  y: number;
  vx: number;
  vy: number;
  facing: 1 | -1;
  grounded: boolean;
  coyote: number;
  jumpBuf: number;
  /** 2 en suelo, 1 tras el primer salto, 0 tras el segundo. */
  jumpsLeft: number;
  hover: number;
  hovering: boolean;
  stun: number;
  charge: number;
  atk: Attack;
  atkT: number;
  atkPower: "normal" | "charged";
  hitBall: boolean;
  hitIds: number[];
  didLunge: boolean;
  anim: number;
  landSquash: number;
  touchCd: number;
  mind: Mind;
};

export type Ball = {
  x: number;
  y: number;
  vx: number;
  vy: number;
  r: number;
  spin: number;
  spinV: number;
  flame: number;
  bounceCd: number;
  flameAcc: number;
};

export type Particle = {
  x: number;
  y: number;
  vx: number;
  vy: number;
  life: number;
  max: number;
  size: number;
  color: string;
  kind: "dust" | "spark" | "confetti" | "flame";
};

export type FloatText = {
  text: string;
  x: number;
  y: number;
  vy: number;
  life: number;
  max: number;
  color: string;
};

/** Burbuja que flota en el campo con el disco morado dentro. */
export type PowerBubble = {
  /** Centro base (sin el vaivén). */
  x: number;
  y: number;
  r: number;
  /** Fase del vaivén vertical (acumula dt, determinista). */
  bobT: number;
  /** Segundos que le quedan antes de desaparecer sola. */
  ttl: number;
};

/** Disco coleccionable que suelta la burbuja al reventar. */
export type PowerItem = {
  x: number;
  y: number;
  r: number;
  /** Segundos que le quedan antes de desaparecer. */
  ttl: number;
};

/** Disco defensivo que oscila verticalmente en una portería (uno por equipo). */
export type GoalShield = {
  /** Segundos restantes (10 → 0). */
  t: number;
};

export type Match = {
  mode: Mode;
  difficulty: Difficulty;
  phase: Phase;
  time: number;
  timer: number;
  sudden: boolean;
  grace: number;
  /** Ventana breve al sacar: la pelota ya bota, pero nadie la toca. */
  kickoffGrace: number;
  pendingOver: boolean;
  scoreL: number;
  scoreR: number;
  fighters: Fighter[];
  ball: Ball;
  particles: Particle[];
  texts: FloatText[];
  shake: number;
  hitstop: number;
  sfx: SfxEvent[];
  banner: string;
  subtitle: string;
  ownGoal: boolean;
  lastTouch: { team: Team; name: string } | null;
  camX: number;
  camY: number;
  /** Ancho de mundo visible: zoom actual de la cámara vertical. */
  camViewW: number;
  camReady: boolean;
  /** Peso suavizado (0..1) con que el rival entra al encuadre vertical. Solo visual. */
  camRival: number;
  /** Deterministic RNG state: same seed → same match, step by step. */
  rng: RngState;
  seed: number;
  /** Burbuja flotando en el campo (null si no hay ninguna). */
  bubble: PowerBubble | null;
  /** Disco suelto esperando a que alguien lo toque (null si no hay). */
  item: PowerItem | null;
  /** Discos defensivos activos, uno por portería (null si ese equipo no tiene).
   *  Cada uno lleva su propia duración: coger otra burbuja reinicia la de ese
   *  equipo a 10 s sin tocar la del rival. */
  shields: { left: GoalShield | null; right: GoalShield | null };
  /** Segundos hasta el próximo spawn de burbuja (solo cuenta sin burbuja ni ítem). */
  nextBubbleIn: number;
};

/**
 * Un solo bot, sin portero artificial. La dificultad cambia lectura de la
 * trayectoria, reacción, precisión al colocarse y probabilidad de saltar/despejar.
 * Ninguna dificultad recibe ayuda de posición: hard sigue siendo vencible.
 */
const DIFF = {
  easy: {
    react: 0.32, predict: 0.06, error: 84, range: 44, power: 0.12, miss: 0.34,
    jumpChance: 0.38, doubleJumpChance: 0.28, holdJump: 0.38,
  },
  normal: {
    react: 0.14, predict: 0.2, error: 30, range: 52, power: 0.24, miss: 0.12,
    jumpChance: 0.7, doubleJumpChance: 0.62, holdJump: 0.62,
  },
  hard: {
    react: 0.06, predict: 0.34, error: 10, range: 60, power: 0.42, miss: 0.035,
    jumpChance: 0.94, doubleJumpChance: 0.9, holdJump: 0.72,
  },
} as const;

export function blankPad(): InputPad {
  return {
    x: 0,
    jump: false,
    jumpPressed: false,
    jumpReleased: false,
    attack: false,
    attackPressed: false,
    attackReleased: false,
    down: false,
    downPressed: false,
  };
}

export function stripEdges(p: InputPad): InputPad {
  return {
    ...p,
    jumpPressed: false,
    jumpReleased: false,
    attackPressed: false,
    attackReleased: false,
    downPressed: false,
  };
}

function mind(): Mind {
  return {
    wait: 0,
    axis: 0,
    jumpPulse: 0,
    doubleJumpNow: false,
    attackPulse: 0,
    downPulse: 0,
    defend: false,
    prevJump: false,
    prevAttack: false,
    prevDown: false,
  };
}

function makeFighter(
  partial: Pick<Fighter, "id" | "team" | "control" | "name" | "character" | "x" | "facing">,
  rng: RngState,
): Fighter {
  return {
    ...partial,
    y: WORLD.ground - PLAYER.hh,
    vx: 0,
    vy: 0,
    grounded: true,
    coyote: JUMP.coyote,
    jumpBuf: 0,
    jumpsLeft: 2,
    hover: JUMP.hoverTime,
    hovering: false,
    stun: 0,
    charge: 0,
    atk: "idle",
    atkT: 0,
    atkPower: "normal",
    hitBall: false,
    hitIds: [],
    didLunge: false,
    anim: nextRand(rng) * 3,
    landSquash: 0,
    touchCd: 0,
    mind: mind(),
  };
}

function makeBall(y = BALL.kickoffY): Ball {
  return {
    x: WORLD.w / 2,
    y,
    vx: 0,
    vy: 0,
    r: WORLD.ballR,
    spin: 0,
    spinV: 0,
    flame: 0,
    bounceCd: 0,
    flameAcc: 0,
  };
}

export function createMatch(opts: {
  mode: Mode;
  difficulty: Difficulty;
  seed?: number;
  characters?: MatchCharacters;
}): Match {
  const { mode, difficulty } = opts;
  const seed = opts.seed ?? randomSeed();
  const rng = createRng(seed);
  const fighters: Fighter[] = [];

  // El roster no puede repetirse. Si una selección llega inválida o duplicada,
  // cae al siguiente id del roster sin tocar el resto del estado del partido.
  let leftCharacter: CharacterId = isCharacterId(opts.characters?.left)
    ? opts.characters.left
    : "tizo";
  let rightCharacter: CharacterId = isCharacterId(opts.characters?.right)
    ? opts.characters.right
    : mode === "demo"
      ? CHARACTERS[Math.floor(nextRand(rng) * CHARACTERS.length)].id
      : "lumi";
  if (rightCharacter === leftCharacter) {
    rightCharacter = mode === "demo"
      ? CHARACTERS[Math.floor(nextRand(rng) * CHARACTERS.length)].id
      : nextCharacterId(leftCharacter);
    if (rightCharacter === leftCharacter) rightCharacter = nextCharacterId(leftCharacter);
  }
  if (leftCharacter === rightCharacter) leftCharacter = nextCharacterId(rightCharacter);

  const push = (team: Team, control: Fighter["control"], x: number) => {
    const character = team === "left" ? leftCharacter : rightCharacter;
    fighters.push(
      makeFighter({
        id: fighters.length,
        team,
        control,
        name: getCharacter(character).name,
        character,
        x,
        facing: team === "left" ? 1 : -1,
      }, rng),
    );
  };

  // Kung Foot 1v1 estricto: un luchador por equipo en todos los modos.
  if (mode === "demo") {
    push("left", "bot", 230);
    push("right", "bot", 810);
  } else if (mode === "cpu") {
    push("left", "p0", 230);
    push("right", "bot", 810);
  } else {
    // online: 1 humano contra 1 humano (cada uno en su celular).
    push("left", "p0", 230);
    push("right", "p1", 810);
  }

  const m: Match = {
    mode,
    difficulty,
    phase: "play",
    time: MATCH_SECONDS,
    timer: 0,
    sudden: false,
    grace: 0,
    kickoffGrace: BALL.kickoffGrace,
    pendingOver: false,
    scoreL: 0,
    scoreR: 0,
    fighters,
    ball: makeBall(),
    particles: [],
    texts: [],
    shake: 0,
    hitstop: 0,
    sfx: [],
    banner: "",
    subtitle: "",
    ownGoal: false,
    lastTouch: null,
    camX: -1,
    camY: 0,
    camViewW: 0,
    camReady: false,
    camRival: 0,
    rng,
    seed,
    bubble: null,
    item: null,
    shields: { left: null, right: null },
    nextBubbleIn: POWERUP.firstIn,
  };

  addText(m, "¡VA!", "#ffb703", WORLD.w / 2, 150);
  m.sfx.push({ id: "whistle", pan: 0, vol: 0.7 });
  return m;
}

function addText(m: Match, text: string, color: string, x: number, y: number) {
  m.texts.push({ text, color, x, y, vy: -22, life: 1.05, max: 1.05 });
  if (m.texts.length > 7) m.texts.shift();
}

function spawn(
  m: Match,
  kind: Particle["kind"],
  x: number,
  y: number,
  n: number,
  color: string,
  speed: number,
) {
  for (let i = 0; i < n; i++) {
    if (m.particles.length > 110) m.particles.shift();
    const a = nextRand(m.rng) * Math.PI * 2;
    const s = speed * (0.35 + nextRand(m.rng));
    m.particles.push({
      x,
      y,
      vx: Math.cos(a) * s,
      vy: Math.sin(a) * s - (kind === "flame" ? 30 : 0),
      life: 0.35 + nextRand(m.rng) * 0.4,
      max: 0.75,
      size: kind === "confetti" ? 4 + nextRand(m.rng) * 4 : 3 + nextRand(m.rng) * 4,
      color,
      kind,
    });
  }
}

function panOf(x: number) {
  return Math.max(-1, Math.min(1, (x / WORLD.w) * 2 - 1));
}

function clamp(v: number, a: number, b: number) {
  return Math.max(a, Math.min(b, v));
}

function reflect(vx: number, vy: number, nx: number, ny: number, e: number) {
  const vn = vx * nx + vy * ny;
  if (vn >= 0) return { vx, vy, hit: false };
  return {
    vx: vx - (1 + e) * vn * nx,
    vy: vy - (1 + e) * vn * ny,
    hit: true,
  };
}

type Body = { x: number; y: number; vx: number; vy: number; hw: number; hh: number };

function bounceCircle(b: Body, cx: number, cy: number, rad: number, e: number) {
  const dx = b.x - cx;
  const dy = b.y - cy;
  const dist = Math.hypot(dx, dy) || 0.0001;
  const min = rad + Math.min(b.hw, b.hh);
  if (dist >= min) return false;
  const nx = dx / dist;
  const ny = dy / dist;
  b.x = cx + nx * min;
  b.y = cy + ny * min;
  const r = reflect(b.vx, b.vy, nx, ny, e);
  if (r.hit) {
    b.vx = r.vx;
    b.vy = r.vy;
  }
  return r.hit;
}

/**
 * Side-view arena with two elevated window goals.
 *
 * The goal mouth is a vertical slot between goalTop and goalBottom. Above and
 * below that slot the wall is solid; below goalBottom it is a full lower wall,
 * so neither the ball nor a fighter can roll into the old floor-level goal.
 * The ball may cross only when its whole diameter fits through the slot. Two
 * round posts per side (top/bottom lip) use bounceCircle as the last line of
 * collision defense, which also keeps 1100 px/s shots tunnel-free at 1/120 s.
 */
export function resolveArena(
  b: Body,
  eWall: number,
  eGround: number,
  opts: { fighter?: boolean; deadBounce?: number } = {},
): { ground: boolean; bonk: boolean } {
  const { hw, hh } = b;
  let ground = false;
  let bonk = false;
  const canUseWindow = !opts.fighter && b.y - hh >= WORLD.goalTop && b.y + hh <= WORLD.goalBottom;

  const bounceMouth = (mouthX: number, fromLeftGoal: boolean) => {
    // Keep the body on the field side of the goal wall. This is used above
    // and below the window, and always for fighters (they never enter a goal).
    if (fromLeftGoal) {
      if (b.x - hw < mouthX) {
        b.x = mouthX + hw;
        if (b.vx < 0) {
          b.vx = -b.vx * eWall;
          bonk = true;
        }
      }
    } else if (b.x + hw > mouthX) {
      b.x = mouthX - hw;
      if (b.vx > 0) {
        b.vx = -b.vx * eWall;
        bonk = true;
      }
    }
  };

  // Left goal: solid frame except the elevated slot.
  if (b.x < WORLD.mouth) {
    if (canUseWindow) {
      if (b.x - hw < WORLD.back) {
        b.x = WORLD.back + hw;
        if (b.vx < 0) {
          b.vx = -b.vx * eWall * 0.72;
          bonk = true;
        }
      }
      if (b.y - hh < WORLD.goalTop) {
        b.y = WORLD.goalTop + hh;
        if (b.vy < 0) {
          b.vy = -b.vy * eWall * 0.55;
          bonk = true;
        }
      } else if (b.y + hh > WORLD.goalBottom) {
        b.y = WORLD.goalBottom - hh;
        if (b.vy > 0) {
          b.vy = -b.vy * eWall * 0.55;
          bonk = true;
        }
      }
    } else {
      bounceMouth(WORLD.mouth, true);
    }
  } else if (b.x - hw < WORLD.mouth && !canUseWindow) {
    bounceMouth(WORLD.mouth, true);
  }

  // Right goal: mirrored frame.
  if (b.x > WORLD.w - WORLD.mouth) {
    if (canUseWindow) {
      if (b.x + hw > WORLD.w - WORLD.back) {
        b.x = WORLD.w - WORLD.back - hw;
        if (b.vx > 0) {
          b.vx = -b.vx * eWall * 0.72;
          bonk = true;
        }
      }
      if (b.y - hh < WORLD.goalTop) {
        b.y = WORLD.goalTop + hh;
        if (b.vy < 0) {
          b.vy = -b.vy * eWall * 0.55;
          bonk = true;
        }
      } else if (b.y + hh > WORLD.goalBottom) {
        b.y = WORLD.goalBottom - hh;
        if (b.vy > 0) {
          b.vy = -b.vy * eWall * 0.55;
          bonk = true;
        }
      }
    } else {
      bounceMouth(WORLD.w - WORLD.mouth, false);
    }
  } else if (b.x + hw > WORLD.w - WORLD.mouth && !canUseWindow) {
    bounceMouth(WORLD.w - WORLD.mouth, false);
  }

  if (b.y - hh < WORLD.ceil) {
    b.y = WORLD.ceil + hh;
    if (b.vy < 0) {
      b.vy = -b.vy * eWall;
      bonk = true;
    }
  }

  if (b.y + hh >= WORLD.ground - 0.05) {
    b.y = WORLD.ground - hh;
    if (b.vy > 0) {
      const impact = b.vy;
      b.vy = -b.vy * eGround;
      if (Math.abs(b.vy) < (opts.deadBounce ?? BALL.deadBounce)) b.vy = 0;
      bonk = impact > 80;
      ground = true;
    } else {
      ground = true;
    }
  }

  // Round top and bottom lips of both elevated windows. Call every post so a
  // fast body cannot skip one when another collision succeeds.
  const postHits = [
    bounceCircle(b, WORLD.mouth, WORLD.goalTop, WORLD.postR, eWall),
    bounceCircle(b, WORLD.mouth, WORLD.goalBottom, WORLD.postR, eWall),
    bounceCircle(b, WORLD.w - WORLD.mouth, WORLD.goalTop, WORLD.postR, eWall),
    bounceCircle(b, WORLD.w - WORLD.mouth, WORLD.goalBottom, WORLD.postR, eWall),
  ];
  return { ground, bonk: bonk || postHits.some(Boolean) };
}

/** Alcance central del golpe; draw.ts lo usa para no dibujar un pie irreal. */
export function attackReach(p: Fighter): number {
  return p.atkPower === "charged" ? 52 : 40;
}

function hitbox(p: Fighter): { x: number; y: number; w: number; h: number } | null {
  if (p.atk === "stomp") {
    return { x: p.x - 24, y: p.y + 8, w: 48, h: 32 };
  }
  if (p.atk !== "active") return null;
  const reach = attackReach(p);
  const w = p.atkPower === "charged" ? 44 : 36;
  const cx = p.x + p.facing * reach;
  return { x: cx - w / 2, y: p.y - 20, w, h: 36 };
}

function rectHitsCircle(
  r: { x: number; y: number; w: number; h: number },
  cx: number,
  cy: number,
  rad: number,
) {
  const nx = clamp(cx, r.x, r.x + r.w);
  const ny = clamp(cy, r.y, r.y + r.h);
  const dx = cx - nx;
  const dy = cy - ny;
  return dx * dx + dy * dy <= rad * rad;
}

function capSpeed(ball: Ball, max: number) {
  const s = Math.hypot(ball.vx, ball.vy);
  if (s > max) {
    ball.vx = (ball.vx / s) * max;
    ball.vy = (ball.vy / s) * max;
  }
}

function touch(m: Match, p: Fighter) {
  m.lastTouch = { team: p.team, name: p.name };
}

/** Velocidad de salida desde ángulo y rapidez; dirección -1 izquierda / +1 derecha. */
export function shotVelocity(angleDeg: number, speed: number, facing: 1 | -1) {
  const rad = (angleDeg * Math.PI) / 180;
  return {
    vx: facing * Math.cos(rad) * speed,
    vy: -Math.sin(rad) * speed,
  };
}

function launchPunch(m: Match, p: Fighter, ball: Ball) {
  const charged = p.atkPower === "charged";
  const angle = charged ? KICK.chargedAngle : KICK.normalAngle;
  const speed = charged ? KICK.chargedSpeed : KICK.normalSpeed;
  // El tiro conserva parte de la velocidad que el balón ya llevaba:
  // cuanto más rápido viene (en cualquier dirección), más fuerte sale.
  // Nunca sale más flojo que el tiro base.
  const rad = (angle * Math.PI) / 180;
  const along = Math.abs(ball.vx * Math.cos(rad) * p.facing - ball.vy * Math.sin(rad));
  const shot = shotVelocity(angle, speed + KICK.keep * along, p.facing);

  const toward = -(ball.vx * p.facing);
  const flame = charged || toward > 250;
  ball.vx = shot.vx;
  ball.vy = shot.vy;
  ball.spinV = p.facing * (flame ? 16 : 10);
  if (flame) ball.flame = 1.45;
  capSpeed(ball, BALL.maxSpeed);
  touch(m, p);
  m.shake = Math.max(m.shake, flame ? 0.7 : 0.38);
  m.hitstop = Math.max(m.hitstop, flame ? 0.05 : 0.028);
  m.sfx.push({ id: flame ? "power" : "kick", pan: panOf(ball.x), vol: flame ? 1 : 0.85 });
  spawn(m, flame ? "flame" : "spark", ball.x, ball.y, flame ? 14 : 7, flame ? "#ffb703" : "#f6efe2", 180);
  if (flame) addText(m, "¡FUEGO!", "#ffb703", ball.x, ball.y - 36);
}

function updateAttack(m: Match, p: Fighter, pad: InputPad, dt: number) {
  if (p.stun > 0) {
    p.atk = "idle";
    p.charge = 0;
    p.atkT = 0;
    return;
  }
  if (p.atk === "idle") {
    if (pad.attack) p.charge = Math.min(0.55, p.charge + dt);

    if (!p.grounded && pad.downPressed && p.vy > -120) {
      p.atk = "stomp";
      p.atkT = 0;
      p.vy = Math.max(p.vy, 980);
      p.charge = 0;
      p.hitBall = false;
      p.hitIds = [];
      m.sfx.push({ id: "stomp", pan: panOf(p.x), vol: 0.55 });
      return;
    }
    if (pad.attackReleased) {
      p.atk = "startup";
      p.atkT = 0;
      p.atkPower = p.charge >= 0.24 ? "charged" : "normal";
      p.hitBall = false;
      p.hitIds = [];
      p.didLunge = false;
      p.charge = 0;
      m.sfx.push({ id: "swish", pan: panOf(p.x), vol: 0.4 });
    } else if (!pad.attack) {
      p.charge = 0;
    }
    return;
  }

  p.atkT += dt;
  if (p.atk === "startup") {
    const need = p.atkPower === "charged" ? 0.08 : 0.04;
    if (p.atkT >= need) {
      p.atk = "active";
      p.atkT = 0;
    }
  } else if (p.atk === "active") {
    if (!p.didLunge) {
      p.didLunge = true;
      p.vx += p.facing * (p.atkPower === "charged" ? 160 : 90);
    }
    const dur = p.atkPower === "charged" ? 0.12 : 0.09;
    if (p.atkT >= dur) {
      p.atk = "recover";
      p.atkT = 0;
    }
  } else if (p.atk === "stomp") {
    p.vy = Math.max(p.vy, 900);
    if (p.grounded) {
      p.atk = "recover";
      p.atkT = 0;
      m.shake = Math.max(m.shake, 0.45);
      m.sfx.push({ id: "land", pan: panOf(p.x), vol: 0.8 });
      spawn(m, "dust", p.x, WORLD.ground - 4, 10, "#d9c4a0", 140);
      if (Math.abs(m.ball.x - p.x) < 78 && m.ball.y > WORLD.ground - 56) {
        const dir = Math.sign(m.ball.x - p.x || p.facing) || p.facing;
        m.ball.vy = -560;
        m.ball.vx += dir * 380;
        m.ball.flame = Math.max(m.ball.flame, 0.35);
        touch(m, p);
        spawn(m, "spark", m.ball.x, m.ball.y, 8, "#ffb703", 160);
      }
    }
  } else if (p.atk === "recover") {
    if (p.atkT >= 0.14) {
      p.atk = "idle";
      p.atkT = 0;
    }
  }
}

function integrateFighter(m: Match, p: Fighter, pad: InputPad, dt: number) {
  p.anim += dt * (0.55 + Math.min(1.4, Math.abs(p.vx) / 280));
  p.landSquash = Math.max(0, p.landSquash - dt * 3.4);
  p.touchCd = Math.max(0, p.touchCd - dt);
  if (p.grounded) {
    p.coyote = JUMP.coyote;
    p.jumpsLeft = 2;
    p.hover = JUMP.hoverTime;
  } else {
    p.coyote = Math.max(0, p.coyote - dt);
  }

  if (p.stun > 0) {
    p.stun -= dt;
    p.vx *= Math.exp(-1.1 * dt);
  } else {
    const charging = p.charge > 0.06 && p.atk === "idle";
    const max = charging ? 230 : 440;
    const accel = p.grounded ? 4200 : 3000;
    if (Math.abs(pad.x) > 0.15) {
      const dir = pad.x > 0 ? 1 : -1;
      p.vx += dir * accel * dt;
      p.facing = dir;
    } else {
      const dec = (p.grounded ? 3800 : 640) * dt;
      if (Math.abs(p.vx) <= dec) p.vx = 0;
      else p.vx -= Math.sign(p.vx) * dec;
    }
    p.vx = clamp(p.vx, -max, max);

    if (pad.jumpPressed) p.jumpBuf = JUMP.buffer;
    else p.jumpBuf = Math.max(0, p.jumpBuf - dt);

    if (p.jumpBuf > 0 && (p.grounded || p.coyote > 0)) {
      // Primer salto desde suelo o coyote.
      p.vy = JUMP.firstVy;
      p.grounded = false;
      p.coyote = 0;
      p.jumpBuf = 0;
      p.jumpsLeft = 1;
      p.hover = JUMP.hoverTime;
      m.sfx.push({ id: "jump", pan: panOf(p.x), vol: 0.45 });
      spawn(m, "dust", p.x, WORLD.ground - 2, 4, "#efe2c8", 70);
    } else if (p.jumpBuf > 0 && !p.grounded && p.jumpsLeft > 0) {
      // Segundo y último salto: más débil, con anillo de aire.
      p.vy = JUMP.secondVy;
      p.grounded = false;
      p.jumpBuf = 0;
      p.jumpsLeft = 0;
      p.hover = JUMP.hoverTime;
      m.sfx.push({ id: "doublejump", pan: panOf(p.x), vol: 0.55 });
      spawn(m, "dust", p.x, p.y + 18, 8, "#f6efe2", 95);
      spawn(m, "spark", p.x, p.y + 8, 4, "#ffb703", 80);
    } else if (pad.jumpReleased && p.vy < 0) {
      // Salto variable en los dos saltos: soltar pronto recorta la subida.
      p.vy *= 0.5;
    }
  }

  updateAttack(m, p, pad, dt);

  let g = 2050;
  if (p.vy > 90) g = 3250;
  else if (Math.abs(p.vy) < 130) g = 1200;
  const canHover =
    pad.jump && !p.grounded && p.vy > -20 && p.hover > 0 && p.stun <= 0 && p.atk !== "stomp";
  p.hovering = canHover;
  if (canHover) {
    g = 680;
    p.hover = Math.max(0, p.hover - dt);
  }

  p.vy += g * dt;
  if (p.vy > 1300) p.vy = 1300;

  const wasGrounded = p.grounded;
  const fallSpeed = p.vy;
  p.x += p.vx * dt;
  p.y += p.vy * dt;
  const body: Body = { x: p.x, y: p.y, vx: p.vx, vy: p.vy, hw: PLAYER.hw, hh: PLAYER.hh };
  const hit = resolveArena(body, 0.2, 0, { fighter: true });
  p.x = body.x;
  p.y = body.y;
  p.vx = body.vx;
  p.vy = body.vy;
  if (hit.ground) {
    p.grounded = true;
    p.vy = 0;
    p.jumpsLeft = 2;
    p.hover = JUMP.hoverTime;
    if (!wasGrounded && fallSpeed > 180) {
      p.landSquash = Math.min(0.28, fallSpeed / 1800);
      if (p.atk !== "stomp") m.sfx.push({ id: "land", pan: panOf(p.x), vol: 0.35 });
      spawn(m, "dust", p.x, WORLD.ground - 2, 5, "#e6d3b0", 90);
    }
  } else {
    p.grounded = false;
  }
}

function separateFighters(list: Fighter[]) {
  for (let i = 0; i < list.length; i++) {
    for (let j = i + 1; j < list.length; j++) {
      const a = list[i];
      const b = list[j];
      let dx = b.x - a.x;
      let dy = b.y - a.y;
      let dist = Math.hypot(dx, dy);
      const min = 36;
      if (dist < 0.001) {
        dx = 1;
        dy = 0;
        dist = 1;
      }
      if (dist >= min) continue;
      const pen = (min - dist) * 0.5;
      const nx = dx / dist;
      const ny = dy / dist;
      a.x -= nx * pen;
      a.y -= ny * pen * 0.25;
      b.x += nx * pen;
      b.y += ny * pen * 0.25;
    }
  }
}

function punchPlayers(m: Match, a: Fighter, b: Fighter) {
  if (a.team === b.team) return;
  if (a.atk !== "active" || a.hitIds.includes(b.id)) return;
  const hb = hitbox(a);
  if (!hb) return;
  if (!rectHitsCircle(hb, b.x, b.y, 22)) return;
  a.hitIds.push(b.id);
  const power = a.atkPower === "charged";
  b.vx = a.facing * (power ? 620 : 460);
  b.vy = power ? -380 : -250;
  b.stun = power ? 0.68 : 0.46;
  b.grounded = false;
  b.atk = "idle";
  b.charge = 0;
  b.x += a.facing * 8;
  m.shake = Math.max(m.shake, power ? 0.5 : 0.3);
  m.hitstop = Math.max(m.hitstop, 0.03);
  m.sfx.push({ id: "hit", pan: panOf(b.x), vol: 0.9 });
  spawn(m, "spark", b.x, b.y - 10, 8, "#f6efe2", 160);
}

/**
 * Contacto del cuerpo por partes: la cabeza es un círculo y el tronco y las
 * piernas una caja. Un solo círculo de radio 28 no servía: el balón se hundía
 * 13 px en la cabeza dibujada (tope -41) y rebotaba 10 px antes de tocar el
 * pecho. Devuelve la normal del contacto y la penetración, o null sin contacto.
 */
function bodyContact(p: Fighter, ball: Ball): { nx: number; ny: number; pen: number } | null {
  // Cabeza: centro (0, -15), radio 24 (draw.ts: cabeza enorme, tope -41).
  // Solo vale por encima del ecuador de la cabeza: si el círculo también
  // cubriera el mentón, robaría los contactos del pecho y los desviaría
  // en diagonal en vez de rebotar recto.
  const hx = ball.x - p.x;
  const hy = ball.y - (p.y - 15);
  if (hy < 0) {
    const hd = Math.hypot(hx, hy) || 0.001;
    const hmin = 24 + ball.r;
    if (hd < hmin) return { nx: hx / hd, ny: hy / hd, pen: hmin - hd };
  }
  // Caja del cuerpo: la misma del motor (PLAYER.hw/hh).
  const cx = clamp(ball.x, p.x - PLAYER.hw, p.x + PLAYER.hw);
  const cy = clamp(ball.y, p.y - PLAYER.hh, p.y + PLAYER.hh);
  const dx = ball.x - cx;
  const dy = ball.y - cy;
  const d = Math.hypot(dx, dy);
  if (d >= ball.r) return null;
  if (d < 0.001) {
    // Centro del balón dentro de la caja: salir por el eje menos penetrado.
    const left = ball.x + ball.r - (p.x - PLAYER.hw);
    const right = p.x + PLAYER.hw - (ball.x - ball.r);
    const top = ball.y + ball.r - (p.y - PLAYER.hh);
    const bottom = p.y + PLAYER.hh - (ball.y - ball.r);
    const m = Math.min(left, right, top, bottom);
    if (m === left) return { nx: -1, ny: 0, pen: left };
    if (m === right) return { nx: 1, ny: 0, pen: right };
    if (m === top) return { nx: 0, ny: -1, pen: top };
    return { nx: 0, ny: 1, pen: bottom };
  }
  return { nx: dx / d, ny: dy / d, pen: ball.r - d };
}

function interactBall(m: Match, p: Fighter, ball: Ball) {
  if (m.kickoffGrace > 0) return;
  const hb = hitbox(p);
  const rx = ball.x - p.x;
  const ry = ball.y - p.y;
  const radial = Math.hypot(rx, ry) || 0.001;
  // Active strike has a short body-radius grace zone. This is the emergency
  // clearance: a defender can dig a ball out from under their feet even when
  // the visual fist is already past it, instead of letting it wedge in a corner.
  // Solo por delante: la gracia radial también agarraba balones detrás de
  // la espalda y los disparaba hacia adelante como si el puño los tocara.
  const closeStrike =
    p.atk === "active" &&
    radial < (p.atkPower === "charged" ? 62 : 52) &&
    rx * p.facing > 0;
  const punched =
    hb && (p.atk === "active" || p.atk === "stomp") && rectHitsCircle(hb, ball.x, ball.y, ball.r);
  if (!p.hitBall && (punched || closeStrike)) {
    p.hitBall = true;
    p.touchCd = 0.12;
    if (p.atk === "stomp") {
      ball.vx = p.facing * 420 + p.vx * 0.15;
      ball.vy = 860;
      ball.spinV = p.facing * 14;
      ball.flame = Math.max(ball.flame, 0.25);
      capSpeed(ball, 1000);
      touch(m, p);
      m.sfx.push({ id: "kick", pan: panOf(ball.x), vol: 0.8 });
      spawn(m, "spark", ball.x, ball.y, 8, "#ffd27a", 150);
    } else {
      launchPunch(m, p, ball);
    }
    const min = 30 + ball.r;
    if (radial < min) {
      ball.x = p.x + (rx / radial) * min;
      ball.y = p.y + (ry / radial) * min;
    }
    return;
  }

  const dx = rx;
  const contact = bodyContact(p, ball);
  if (!contact) return;
  const { nx, ny, pen } = contact;
  if (p.grounded && ny > 0.35) {
    ball.x += Math.sign(dx || p.facing) * pen;
  } else {
    ball.x += nx * pen;
    ball.y += ny * pen;
  }

  const header = !p.grounded && ny < -0.4 && p.atk !== "active" && p.atk !== "stomp";
  if (header && p.touchCd <= 0) {
    p.touchCd = 0.16;
    const radH = (KICK.headerAngle * Math.PI) / 180;
    const along = Math.abs(ball.vx * Math.cos(radH) * p.facing - ball.vy * Math.sin(radH));
    const shot = shotVelocity(KICK.headerAngle, KICK.headerSpeed + KICK.keep * along, p.facing);
    ball.vx = shot.vx;
    ball.vy = shot.vy;
    ball.spinV = p.facing * 8;
    capSpeed(ball, BALL.maxSpeed);
    touch(m, p);
    m.sfx.push({
      id: "bounce",
      pan: panOf(ball.x),
      vol: clamp(Math.hypot(ball.vx, ball.vy) / 900, 0.25, 0.85),
    });
    spawn(m, "spark", ball.x, ball.y, 5, "#f6efe2", 90);
    return;
  }

  const vn = (ball.vx - p.vx) * nx + (ball.vy - p.vy) * ny;
  if (vn < 0) {
    const j = -(1.25) * vn;
    ball.vx += j * nx;
    ball.vy += j * ny;
  }
  if (Math.abs(p.vx) > 50 && Math.sign(p.vx) === Math.sign(nx || p.vx)) {
    const want = p.vx * 1.12;
    ball.vx += (want - ball.vx) * 0.4;
  }
  const sp = Math.hypot(ball.vx, ball.vy);
  const cap = 460;
  if (sp > cap && p.atk !== "active") {
    ball.vx *= cap / sp;
    ball.vy *= cap / sp;
  }
  if (vn < -160 && p.touchCd <= 0) {
    p.touchCd = 0.1;
    touch(m, p);
    m.sfx.push({
      id: "bounce",
      pan: panOf(ball.x),
      vol: clamp(Math.abs(vn) / 900, 0.2, 0.8),
    });
  }
}

/**
 * Power-up de la burbuja (disco morado).
 *
 * Flujo: la burbuja flota en el campo → un golpe la revienta y suelta el
 * disco → al tocar el disco suelto, aparece un disco defensivo que oscila
 * verticalmente en la portería de quien lo cogió y rechaza el balón durante
 * 7 segundos. Todo es matemática pura con el RNG del partido: mismo seed,
 * mismo spawn, misma oscilación, mismo rebote.
 */

/** Posición vertical efectiva de la burbuja (con el vaivén). */
export function bubbleY(b: PowerBubble): number {
  return b.y + Math.sin(b.bobT * POWERUP.bobSpeed) * POWERUP.bobAmp;
}

/** Posición del disco defensivo de un equipo, o null si no tiene escudo. */
export function shieldDiscFor(m: Match, team: Team): { x: number; y: number; r: number } | null {
  const s = m.shields[team];
  if (!s) return null;
  const left = team === "left";
  const x = left ? WORLD.mouth : WORLD.w - WORLD.mouth;
  const center = (WORLD.goalTop + WORLD.goalBottom) / 2;
  // La amplitud deja el borde del disco a 2 px del borde de los discos de los
  // postes: nunca se solapa con ellos en los extremos del vaivén.
  const amp = (WORLD.goalBottom - WORLD.goalTop) / 2 - POWERUP.discR - WORLD.postR - 2;
  const elapsed = POWERUP.shieldSecs - s.t;
  const y = center + amp * Math.sin(elapsed * POWERUP.discSpeed);
  return { x, y, r: POWERUP.discR };
}

/** Discos defensivos activos (uno por portería como máximo). */
export function shieldDiscs(m: Match): { x: number; y: number; r: number; team: Team; t: number }[] {
  const out: { x: number; y: number; r: number; team: Team; t: number }[] = [];
  (["left", "right"] as Team[]).forEach((team) => {
    const d = shieldDiscFor(m, team);
    const s = m.shields[team];
    if (d && s) out.push({ ...d, team, t: s.t });
  });
  return out;
}

function spawnBubble(m: Match) {
  // Zona central del campo, a altura alcanzable con salto + golpe.
  const x = 380 + nextRand(m.rng) * 280;
  const y = 280 + nextRand(m.rng) * 100;
  m.bubble = { x, y, r: POWERUP.bubbleR, bobT: 0, ttl: POWERUP.bubbleSecs };
  m.nextBubbleIn = POWERUP.nextMin + nextRand(m.rng) * (POWERUP.nextMax - POWERUP.nextMin);
}

function updatePowerup(m: Match, dt: number) {
  // Spawn: solo cuenta atrás cuando no hay burbuja ni ítem en juego.
  if (!m.bubble && !m.item) {
    m.nextBubbleIn -= dt;
    if (m.nextBubbleIn <= 0) spawnBubble(m);
  }

  // Vaivén y vida de la burbuja.
  if (m.bubble) {
    m.bubble.bobT += dt;
    m.bubble.ttl -= dt;
    if (m.bubble.ttl <= 0) {
      spawn(m, "spark", m.bubble.x, bubbleY(m.bubble), 6, POWERUP.purple, 120);
      m.bubble = null;
    }
  }

  // Vida del ítem suelto.
  if (m.item) {
    m.item.ttl -= dt;
    if (m.item.ttl <= 0) {
      spawn(m, "spark", m.item.x, m.item.y, 6, POWERUP.purple, 120);
      m.item = null;
    }
  }

  // Cada escudo se agota a los 10 segundos, con su propio temporizador.
  (["left", "right"] as Team[]).forEach((team) => {
    const s = m.shields[team];
    if (!s) return;
    s.t -= dt;
    if (s.t <= 0) {
      const d = shieldDiscFor(m, team);
      if (d) spawn(m, "spark", d.x, d.y, 10, POWERUP.purple, 160);
      m.shields[team] = null;
    }
  });

  // Reventar la burbuja con un golpe (golpe activo o plancha).
  if (m.bubble) {
    const by = bubbleY(m.bubble);
    for (const f of m.fighters) {
      const hb = hitbox(f);
      if (!hb) continue;
      if (!rectHitsCircle(hb, m.bubble.x, by, m.bubble.r)) continue;
      const bx = m.bubble.x;
      spawn(m, "spark", bx, by, 14, POWERUP.purple, 220);
      spawn(m, "spark", bx, by, 8, "#f6efe2", 160);
      m.sfx.push({ id: "hit", pan: panOf(bx), vol: 0.8 });
      m.bubble = null;
      m.item = { x: bx, y: by, r: POWERUP.itemR, ttl: POWERUP.itemSecs };
      break;
    }
  }

  // Tocar el disco suelto: el escudo aparece en la portería de quien lo coge.
  if (m.item) {
    for (const f of m.fighters) {
      const box = { x: f.x - PLAYER.hw, y: f.y - PLAYER.hh, w: PLAYER.hw * 2, h: PLAYER.hh * 2 };
      if (!rectHitsCircle(box, m.item.x, m.item.y, m.item.r)) continue;
      const ix = m.item.x;
      const iy = m.item.y;
      m.item = null;
      // Escudo propio: reinicia su duración a 10 s (no se suma) y no toca
      // el escudo del rival, que sigue con su duración independiente.
      m.shields[f.team] = { t: POWERUP.shieldSecs };
      spawn(m, "spark", ix, iy, 16, POWERUP.purple, 240);
      m.sfx.push({ id: "power", pan: panOf(ix), vol: 1 });
      addText(m, "¡ESCUDO!", POWERUP.purple, ix, iy - 40);
      break;
    }
  }

  // El balón rebota en los discos defensivos (como en los postes).
  for (const disc of shieldDiscs(m)) {
    const b = m.ball;
    const body: Body = { x: b.x, y: b.y, vx: b.vx, vy: b.vy, hw: b.r, hh: b.r };
    if (bounceCircle(body, disc.x, disc.y, disc.r, BALL.wallRestitution)) {
      b.x = body.x;
      b.y = body.y;
      b.vx = body.vx;
      b.vy = body.vy;
      capSpeed(b, BALL.maxSpeed);
      if (b.bounceCd <= 0 && Math.hypot(b.vx, b.vy) > 55) {
        b.bounceCd = 0.07;
        m.sfx.push({ id: "bounce", pan: panOf(b.x), vol: 0.7 });
        spawn(m, "spark", b.x, b.y, 4, POWERUP.purple, 120);
      }
    }
  }
}

function stepBall(m: Match, dt: number) {

  const ball = m.ball;
  ball.flame = Math.max(0, ball.flame - dt * 0.55);
  ball.bounceCd = Math.max(0, ball.bounceCd - dt);

  // Vuelo libre: sin arrastre horizontal. Integramos la posición con la
  // fórmula exacta de aceleración constante y dejamos la velocidad al final.
  if (BALL.airDrag > 0) {
    ball.vx *= Math.exp(-BALL.airDrag * dt);
  }
  const vx0 = ball.vx;
  const vy0 = ball.vy;
  ball.x += vx0 * dt;
  ball.y += vy0 * dt + 0.5 * BALL.gravity * dt * dt;
  ball.vy = vy0 + BALL.gravity * dt;
  ball.spinV *= Math.exp(-1.4 * dt);
  ball.spin += ball.spinV * dt + ball.vx * dt * 0.01;

  const body: Body = { x: ball.x, y: ball.y, vx: ball.vx, vy: ball.vy, hw: ball.r, hh: ball.r };
  const before = ball.vy;
  const hit = resolveArena(body, BALL.wallRestitution, BALL.floorRestitution, {
    deadBounce: BALL.deadBounce,
  });
  ball.x = body.x;
  ball.y = body.y;
  ball.vx = body.vx;
  ball.vy = body.vy;

  if (ball.y + ball.r >= WORLD.ground - 0.5 && Math.abs(ball.vy) < BALL.settleSpeed) {
    ball.y = WORLD.ground - ball.r;
    ball.vy = 0;
    const fr = BALL.rollingFriction * dt;
    if (Math.abs(ball.vx) <= fr) ball.vx = 0;
    else ball.vx -= Math.sign(ball.vx) * fr;
  } else if (hit.ground && before > 120) {
    ball.spinV += ball.vx * 0.02;
  }

  if (hit.bonk && ball.bounceCd <= 0 && Math.hypot(ball.vx, ball.vy) > 55) {
    ball.bounceCd = 0.07;
    m.sfx.push({
      id: "bounce",
      pan: panOf(ball.x),
      vol: clamp(Math.hypot(ball.vx, ball.vy) / BALL.maxSpeed, 0.18, 0.9),
    });
    spawn(m, "dust", ball.x, ball.y, 3, "#f6efe2", 60);
  }

  if (ball.flame > 0.15) {
    ball.flameAcc += dt;
    if (ball.flameAcc > 0.03) {
      ball.flameAcc = 0;
      spawn(m, "flame", ball.x, ball.y, 1, nextRand(m.rng) > 0.5 ? "#ff7a18" : "#ffb703", 40);
    }
  }

  capSpeed(ball, BALL.maxSpeed);
}

export function checkGoal(m: Match) {
  if (m.phase !== "play") return;
  const b = m.ball;
  // The whole ball must be between the crossbar and the lower lip. This
  // deliberately excludes the floor: rolling underneath the goal never scores.
  const inOpening = b.y - b.r >= WORLD.goalTop && b.y + b.r <= WORLD.goalBottom;
  if (!inOpening) return;

  let team: Team | null = null;
  let mouthX = 0;
  if (b.x < WORLD.mouth - 1) {
    team = "right";
    mouthX = WORLD.mouth;
  } else if (b.x > WORLD.w - WORLD.mouth + 1) {
    team = "left";
    mouthX = WORLD.w - WORLD.mouth;
  }
  if (!team) return;

  // El power-up no se limpia: burbuja, ítem y escudos persisten tras el gol.
  if (team === "left") m.scoreL += 1;
  else m.scoreR += 1;

  const last = m.lastTouch;
  m.ownGoal = !!last && last.team !== team;
  const flaming = b.flame > 0.25;
  m.banner = m.ownGoal ? "¡AUTOGOL!" : flaming ? "¡DE FUEGO!" : "¡GOL!";
  m.subtitle = last ? last.name : "";
  m.phase = "goal";
  m.timer = 1.7;
  m.pendingOver = m.time <= 0;
  m.shake = 1;
  m.hitstop = 0.06;
  m.sfx.push({ id: "goal", pan: team === "left" ? 0.65 : -0.65, vol: 1 });

  // Celebration exits through the goal mouth, not from the floor.
  const outward = team === "left" ? -1 : 1;
  const before = m.particles.length;
  for (let i = 0; i < 72; i++) {
    spawn(m, "confetti", mouthX, (WORLD.goalTop + WORLD.goalBottom) / 2, 1, FX_COLORS[i % FX_COLORS.length], 300);
  }
  for (let i = before; i < m.particles.length; i++) {
    m.particles[i].vx += outward * (120 + nextRand(m.rng) * 190);
    m.particles[i].vy -= 80 + nextRand(m.rng) * 160;
  }
  const sparksBefore = m.particles.length;
  for (let i = 0; i < 24; i++) {
    spawn(m, "spark", mouthX, (WORLD.goalTop + WORLD.goalBottom) / 2, 1, i % 3 === 0 ? "#ffd27a" : "#f6efe2", 420);
  }
  for (let i = sparksBefore; i < m.particles.length; i++) {
    m.particles[i].vx += outward * (60 + nextRand(m.rng) * 160);
    m.particles[i].vy -= 120 + nextRand(m.rng) * 220;
  }
}

function resetKickoff(m: Match) {
  m.ball = makeBall(BALL.kickoffY);
  m.phase = "play";
  // La cámara vuelve al encuadre del saque: sin esto, tras el gol seguía
  // enfocada en la red y el balón "saltaba" al reencuadrar de golpe.
  m.camX = -1;
  m.camViewW = 0;
  m.camReady = false;
  m.pendingOver = false;
  m.grace = 0;
  m.kickoffGrace = BALL.kickoffGrace;
  m.banner = "";
  m.subtitle = "";
  m.ownGoal = false;
  m.lastTouch = null;
  // El power-up persiste tras el saque (burbuja, ítem y escudos siguen con
  // su duración). La cuenta atrás de la próxima burbuja solo corre cuando no
  // hay burbuja ni ítem en juego, así que este reinicio no les afecta.
  m.nextBubbleIn = POWERUP.firstIn;

  for (const f of m.fighters) {
    const home = homeX(m, f);
    f.x = home;
    f.y = WORLD.ground - PLAYER.hh;
    f.vx = 0;
    f.vy = 0;
    f.grounded = true;
    f.coyote = JUMP.coyote;
    f.jumpBuf = 0;
    f.jumpsLeft = 2;
    f.stun = 0;
    f.atk = "idle";
    f.charge = 0;
    f.hover = JUMP.hoverTime;
    f.facing = f.team === "left" ? 1 : -1;
    f.hitBall = false;
    f.hitIds = [];
  }
  addText(m, "¡VA!", "#ffb703", WORLD.w / 2, 160);
  m.sfx.push({ id: "whistle", pan: 0, vol: 0.55 });
}

function homeX(_m: Match, f: Fighter) {
  return f.team === "left" ? 240 : 800;
}

function finishClock(m: Match) {
  if (m.scoreL !== m.scoreR) {
    m.phase = "over";
    m.timer = 0;
    m.sfx.push({ id: "whistle", pan: 0, vol: 0.8 });
  } else if (!m.sudden) {
    m.sudden = true;
    m.grace = 0;
    m.ball.flame = Math.max(m.ball.flame, 0.8);
    addText(m, "¡GOL DE ORO!", "#ffb703", WORLD.w / 2, 140);
    m.sfx.push({ id: "sudden", pan: 0, vol: 0.9 });
  }
}

function nearest(m: Match, f: Fighter, same: boolean) {
  let best: Fighter | null = null;
  let bestD = 1e9;
  for (const o of m.fighters) {
    if (o === f) continue;
    if (same ? o.team !== f.team : o.team === f.team) continue;
    const d = Math.hypot(o.x - f.x, o.y - f.y);
    if (d < bestD) {
      bestD = d;
      best = o;
    }
  }
  return best;
}

function decide(m: Match, f: Fighter) {
  const diff = DIFF[m.difficulty];
  const ball = m.ball;
  const attackDir: 1 | -1 = f.team === "left" ? 1 : -1;
  const ownMouth = f.team === "left" ? WORLD.mouth : WORLD.w - WORLD.mouth;
  const ownHalf = f.team === "left" ? ball.x < WORLD.w * 0.47 : ball.x > WORLD.w * 0.53;
  const headingToOwn = -attackDir * ball.vx > 170;
  const travel = diff.predict;
  const predX = ball.x + ball.vx * travel;
  const predY = ball.y + ball.vy * travel + 0.5 * BALL.gravity * travel * travel;
  const nearOwnGoal = f.team === "left" ? ball.x < 390 : ball.x > WORLD.w - 390;

  // No keeper role: the same bot switches to emergency defense whenever the
  // ball is in its half or its trajectory is heading toward its elevated goal.
  const defend = ownHalf || (headingToOwn && nearOwnGoal) || (nearOwnGoal && predY < WORLD.goalBottom + 90);
  f.mind.defend = defend;

  // Power-up: si hay burbuja o ítem y está más cerca que el balón, ir por él.
  // El ítem se coge solo con tocarlo; la burbuja hay que reventarla con golpe.
  const powerTarget = m.item
    ? { x: m.item.x, y: m.item.y, isItem: true }
    : m.bubble
      ? { x: m.bubble.x, y: bubbleY(m.bubble), isItem: false }
      : null;
  let chasePower = false;
  if (powerTarget) {
    const dPower = Math.hypot(powerTarget.x - f.x, powerTarget.y - f.y);
    const dBall = Math.hypot(ball.x - f.x, ball.y - f.y);
    chasePower = dPower < dBall;
  }
  if (chasePower && powerTarget) {
    const pdx = powerTarget.x - f.x;
    f.mind.axis = Math.abs(pdx) < 10 ? 0 : Math.sign(pdx);
    // Saltar para alcanzar una burbuja alta.
    const powerAbove = powerTarget.y < f.y - 44;
    if (
      powerAbove &&
      Math.abs(pdx) < 150 &&
      f.grounded &&
      f.stun <= 0 &&
      f.mind.jumpPulse <= 0 &&
      nextRand(m.rng) < diff.jumpChance
    ) {
      f.mind.jumpPulse = diff.holdJump;
    }
    if (
      !f.grounded &&
      f.jumpsLeft > 0 &&
      powerAbove &&
      Math.abs(pdx) < 205 &&
      f.vy > -210 &&
      f.stun <= 0 &&
      nextRand(m.rng) < diff.doubleJumpChance
    ) {
      f.mind.doubleJumpNow = true;
      f.mind.jumpPulse = Math.max(f.mind.jumpPulse, 0.24);
    }
    // Golpe para reventar la burbuja cuando está a alcance.
    if (
      !powerTarget.isItem &&
      Math.abs(pdx) < 70 &&
      Math.abs(powerTarget.y - (f.y - 8)) < 80 &&
      f.stun <= 0 &&
      f.atk === "idle" &&
      f.mind.attackPulse <= 0
    ) {
      f.mind.attackPulse = 0.12;
    }
  }

  // Approach from the field side of the ball so every touch/header sends it
  // away from the striker's own goal. Under pressure, cut the angle and get
  // under the incoming trajectory instead of parking in front of the net.
  let target = chasePower && powerTarget ? powerTarget.x : defend ? predX : ball.x - attackDir * 42;
  if (defend && Math.abs(ball.x - ownMouth) > 250) {
    target = Math.min(target, ownMouth + attackDir * 280);
    if (f.team === "right") target = Math.max(target, ownMouth - 280);
  }
  target += (nextRand(m.rng) - 0.5) * diff.error;

  const goalSideLimit = 36;
  if (f.team === "left") target = clamp(target, ownMouth + goalSideLimit, WORLD.w - 70);
  else target = clamp(target, 70, ownMouth - goalSideLimit);

  const dx = target - f.x;
  f.mind.axis = Math.abs(dx) < 10 ? 0 : Math.sign(dx);

  // Easy bot is allowed to lose the plot occasionally; hard almost never does.
  if (nextRand(m.rng) < diff.miss) return;

  const closeX = Math.abs(ball.x - f.x);
  const verticalGap = ball.y - (f.y - 8);
  const inFront = attackDir === 1 ? ball.x > f.x - 20 : ball.x < f.x + 20;

  // Elevate the bot's own body: intercept balls crossing the window, never
  // just stand under it. The long hold enables hover around the apex.
  const ballAbove = verticalGap < -44;
  const shotToWindow = ball.y < WORLD.goalBottom + 30 && nearOwnGoal;
  if (
    (ballAbove || shotToWindow) &&
    closeX < 150 &&
    f.grounded &&
    f.stun <= 0 &&
    f.mind.jumpPulse <= 0 &&
    nextRand(m.rng) < diff.jumpChance
  ) {
    f.mind.jumpPulse = diff.holdJump;
  }

  // Segundo salto para pelotas altas o ventana: el bot espera al ápice para
  // no desperdiciarlo y la dificultad controla cuánto lo intenta.
  if (
    !f.grounded &&
    f.jumpsLeft > 0 &&
    (ballAbove || shotToWindow) &&
    closeX < 205 &&
    f.vy > -210 &&
    f.stun <= 0 &&
    nextRand(m.rng) < diff.doubleJumpChance
  ) {
    f.mind.doubleJumpNow = true;
    f.mind.jumpPulse = Math.max(f.mind.jumpPulse, 0.24);
  }

  const canReach = closeX < diff.range + 10 && Math.abs(verticalGap) < 70 && inFront;
  const closeClear = defend && Math.abs(ball.x - f.x) < 72 && Math.abs(verticalGap) < 82;
  const airborneRead = !f.grounded && Math.abs(verticalGap) < 78;
  if ((canReach || closeClear || airborneRead) && f.stun <= 0 && f.atk === "idle" && f.mind.attackPulse <= 0) {
    const incoming = -(ball.vx * attackDir);
    // En ataque busca el arco cargado; en defensa despeja con la potencia que
    // permita sacar la pelota sin regalarla al rival.
    const attackingWindow = !defend && Math.abs(ball.x - ownMouth) > 260;
    const power = attackingWindow || incoming > 220 || nextRand(m.rng) < diff.power;
    f.facing = attackDir;
    f.mind.attackPulse = power ? 0.38 : 0.12;
    f.mind.axis = 0;
  }
  if (f.mind.attackPulse > 0 && f.stun <= 0) f.facing = attackDir;

  // The one-on-one means there is always an opponent nearby: punch when the
  // ball is behind them so the rebound/clear leaves the danger zone.
  const foe = nearest(m, f, false);
  if (
    foe &&
    foe.stun <= 0 &&
    Math.abs(foe.x - f.x) < 44 &&
    Math.abs(foe.y - f.y) < 34 &&
    Math.abs(foe.x - ball.x) < 38 &&
    f.mind.attackPulse <= 0 &&
    f.atk === "idle"
  ) {
    f.mind.axis = Math.sign(foe.x - f.x) || f.facing;
    f.mind.attackPulse = 0.12;
  }

  if (!f.grounded && ball.y > f.y + 16 && closeX < 42 && f.vy > -80) {
    if (f.mind.downPulse <= 0) f.mind.downPulse = 0.12;
  }
}

function botPad(m: Match, f: Fighter, dt: number): InputPad {
  f.mind.wait -= dt;
  if (f.mind.wait <= 0) {
    decide(m, f);
    const react = DIFF[m.difficulty].react;
    f.mind.wait = react * (0.65 + nextRand(m.rng) * 0.7);
  }
  const doubleJumpNow = f.mind.doubleJumpNow;
  const jump = f.mind.jumpPulse > 0 || doubleJumpNow;
  const attack = f.mind.attackPulse > 0;
  const down = f.mind.downPulse > 0;
  f.mind.jumpPulse = Math.max(0, f.mind.jumpPulse - dt);
  f.mind.attackPulse = Math.max(0, f.mind.attackPulse - dt);
  f.mind.downPulse = Math.max(0, f.mind.downPulse - dt);
  const pad: InputPad = {
    x: f.mind.axis,
    jump,
    jumpPressed: doubleJumpNow || (jump && !f.mind.prevJump),
    jumpReleased: !jump && f.mind.prevJump,
    attack,
    attackPressed: attack && !f.mind.prevAttack,
    attackReleased: !attack && f.mind.prevAttack,
    down,
    downPressed: down && !f.mind.prevDown,
  };
  f.mind.doubleJumpNow = false;
  f.mind.prevJump = jump;
  f.mind.prevAttack = attack;
  f.mind.prevDown = down;
  return pad;
}

function stepParticles(m: Match, dt: number) {
  for (let i = m.particles.length - 1; i >= 0; i--) {
    const p = m.particles[i];
    p.life -= dt;
    if (p.life <= 0) {
      m.particles.splice(i, 1);
      continue;
    }
    p.vy += (p.kind === "flame" ? -40 : 520) * dt;
    p.x += p.vx * dt;
    p.y += p.vy * dt;
  }
  for (let i = m.texts.length - 1; i >= 0; i--) {
    const t = m.texts[i];
    t.life -= dt;
    t.y += t.vy * dt;
    if (t.life <= 0) m.texts.splice(i, 1);
  }
}

/**
 * The goal is not a freeze-frame: the ball keeps flying into the net while
 * the celebration runs. The net catches it (strong drag inside the pocket),
 * the back of the net stops it with a soft rebound, and it settles on the
 * lower lip. Pure math, no randomness: both online peers run the same steps,
 * so the sync hash still matches.
 */
function stepGoalBall(m: Match, dt: number) {
  const b = m.ball;
  const left = b.x < WORLD.w / 2;
  const backX = left ? WORLD.back : WORLD.w - WORLD.back;
  const inPocket = left ? b.x < WORLD.mouth : b.x > WORLD.w - WORLD.mouth;
  const drag = inPocket ? 7 : 0.5;
  const damp = Math.max(0, 1 - drag * dt);
  b.vx *= damp;
  b.vy *= damp;
  b.vy += BALL.gravity * dt * 0.55;
  b.x += b.vx * dt;
  b.y += b.vy * dt;
  b.spin += b.spinV * dt;
  b.flame = Math.max(0, b.flame - dt * 1.6);
  // Back of the net: soft stop, shake pulse and sparks on a hard impact.
  const backLimit = left ? backX + b.r : backX - b.r;
  if (left ? b.x < backLimit : b.x > backLimit) {
    const impact = Math.abs(b.vx);
    b.x = backLimit;
    if (impact > 60) {
      b.vx = -b.vx * 0.18;
      m.shake = Math.max(m.shake, 0.9);
      spawn(m, "spark", backX, b.y, 6, "#ffd27a", 150);
    } else {
      b.vx = 0;
    }
  }
  // The frame is solid inside the pocket: the ball cannot leave through the
  // crossbar or the lower lip, and it rests on the lip when it drops.
  if (b.y - b.r < WORLD.goalTop) {
    b.y = WORLD.goalTop + b.r;
    b.vy = Math.abs(b.vy) * 0.2;
  }
  if (b.y + b.r > WORLD.goalBottom) {
    b.y = WORLD.goalBottom - b.r;
    if (b.vy > 0) b.vy = -b.vy * 0.15;
    b.vx *= Math.max(0, 1 - 6 * dt);
  }
  // Never drift back out onto the field.
  if (left) b.x = Math.min(b.x, WORLD.mouth - 1);
  else b.x = Math.max(b.x, WORLD.w - WORLD.mouth + 1);
}

/** Returns true if this step requested a hit-stop (caller should not chain physics). */
export function stepMatch(m: Match, pads: Pads, dt: number): boolean {
  if (m.phase === "goal") {
    m.timer -= dt;
    stepGoalBall(m, dt);
    stepParticles(m, dt);
    if (m.timer <= 0) {
      if (m.pendingOver) {
        m.phase = "over";
        m.sfx.push({ id: "whistle", pan: 0, vol: 0.8 });
      } else resetKickoff(m);
    }
    return false;
  }
  if (m.phase === "over") {
    stepParticles(m, dt);
    return false;
  }

  m.kickoffGrace = Math.max(0, m.kickoffGrace - dt);

  const inputs = m.fighters.map((f) =>
    f.control === "p0" ? pads.p0 : f.control === "p1" ? pads.p1 : botPad(m, f, dt),
  );

  for (let i = 0; i < m.fighters.length; i++) {
    integrateFighter(m, m.fighters[i], inputs[i], dt);
  }
  separateFighters(m.fighters);
  for (const f of m.fighters) {
    const b: Body = { x: f.x, y: f.y, vx: f.vx, vy: f.vy, hw: PLAYER.hw, hh: PLAYER.hh };
    resolveArena(b, 0.1, 0, { fighter: true });
    f.x = b.x;
    f.y = Math.min(b.y, WORLD.ground - PLAYER.hh);
    f.vx = b.vx;
  }

  stepBall(m, dt);
  for (const f of m.fighters) interactBall(m, f, m.ball);
  // Arena again so a header can't leave the ball in the floor.
  {
    const b = m.ball;
    const body: Body = { x: b.x, y: b.y, vx: b.vx, vy: b.vy, hw: b.r, hh: b.r };
    resolveArena(body, 0.8, 0.6);
    b.x = body.x;
    b.y = body.y;
    b.vx = body.vx;
    b.vy = body.vy;
  }
  for (let i = 0; i < m.fighters.length; i++) {
    for (let j = 0; j < m.fighters.length; j++) {
      if (i === j) continue;
      punchPlayers(m, m.fighters[i], m.fighters[j]);
    }
  }

  updatePowerup(m, dt);

  checkGoal(m);

  if (m.phase === "play" && !m.sudden) {
    m.time -= dt;
    if (m.time <= 0) {
      m.time = 0;
      const hot = Math.hypot(m.ball.vx, m.ball.vy) > 620 || m.ball.flame > 0.2;
      if (hot && m.grace <= 0) m.grace = 0.45;
      if (m.grace > 0) {
        m.grace -= dt;
        if (m.grace <= 0) finishClock(m);
      } else finishClock(m);
    }
  }

  stepParticles(m, dt);
  return m.hitstop > 0;
}
