import { POWERUP, WORLD } from "./constants.ts";
import { getCharacter, INK, PAPER, type CharacterId } from "./characters.ts";
import { drawFighter, type FighterMood } from "./chibi.ts";
import { attackReach, bubbleY, shieldDiscs, type Ball, type Fighter, type Match, type Particle } from "./engine.ts";

export type Camera = { x: number; y: number; w: number; h: number; scale: number; ox: number; oy: number };
const CAMERA: Camera = { x: 0, y: 0, w: WORLD.w, h: WORLD.h, scale: 1, ox: 0, oy: 0 };

export const CAMERA_MARGIN = 72;
export const CAMERA_LOOKAHEAD_SECONDS = 0.2;
const CAMERA_HYSTERESIS = 12;
const CAMERA_ZOOM_OUT_K = 4.5;
const CAMERA_ZOOM_IN_K = 2.7;
const CAMERA_PAN_K = 5.8;
const CAMERA_SAFE_MARGIN = 10;

const RIVAL_BLEND = 200;
const RIVAL_WEIGHT_K = 4;

function smoothstep(edge0: number, edge1: number, x: number) {
  const t = clampValue((x - edge0) / (edge1 - edge0), 0, 1);
  return t * t * (3 - 2 * t);
}

function clampValue(value: number, min: number, max: number) {
  return Math.max(min, Math.min(max, value));
}

/**
 * Cámara del juego.
 *
 * Horizontal conserva exactamente el encuadre fijo de siempre. En vertical
 * encuadra a p0 + pelota (y al rival cuando entra en escena) con un zoom que
 * se abre hacia WORLD.w si alguno se aleja. El estado vive en Match para que
 * no haya asignaciones por frame y para conservar la suavidad entre goles.
 */
export function frameOf(
  canvasW: number,
  canvasH: number,
  m: Match,
  focusX: number,
  dt: number,
  focusControl: "p0" | "p1" = "p0",
): Camera {
  const aspect = canvasW / Math.max(1, canvasH);
  const minViewW = Math.min(WORLD.w, WORLD.h * aspect);

  if (aspect >= 1.05) {
    // Horizontal: sin cambios respecto al comportamiento original.
    const scale = Math.min(canvasW / WORLD.w, canvasH / WORLD.h);
    CAMERA.x = 0;
    CAMERA.y = 0;
    CAMERA.w = WORLD.w;
    CAMERA.h = WORLD.h;
    CAMERA.scale = scale;
    CAMERA.ox = (canvasW - WORLD.w * scale) / 2;
    CAMERA.oy = (canvasH - WORLD.h * scale) / 2;
    m.camX = 0;
    m.camY = 0;
    m.camViewW = WORLD.w;
    m.camReady = true;
    return CAMERA;
  }

  const human = m.fighters.find((f) => f.control === focusControl) ?? m.fighters[0];
  const rival = human ? m.fighters.find((f) => f.team !== human.team) : m.fighters[1];
  const ball = m.ball;
  const lookAhead = clampValue(ball.vx * CAMERA_LOOKAHEAD_SECONDS, -150, 150);
  const ballAheadX = ball.x + lookAhead;

  let minX = Math.min(human?.x ?? focusX, ball.x, ballAheadX);
  let maxX = Math.max(human?.x ?? focusX, ball.x, ballAheadX);

  // El rival entra en el encuadre cuando está cerca de la jugada, no siempre:
  // así el 1v1 no fuerza el zoom máximo desde el saque.
  // La entrada es GRADUAL (peso 0..1 según la distancia) y no un if: con el
  // umbral duro, justo al caer la pelota en el saque el rival cruzaba los
  // 230 px, el encuadre pegaba un salto y se veía como si la cámara
  // "repitiera" el lanzamiento (dos encuadres peleándose).
  const safeDt = Math.min(0.05, Math.max(0.001, dt));
  let rivalTarget = 0;
  if (rival) {
    const wHuman = human ? 1 - smoothstep(285, 285 + RIVAL_BLEND, Math.abs(rival.x - human.x)) : 0;
    const wBall = 1 - smoothstep(230, 230 + RIVAL_BLEND, Math.abs(rival.x - ball.x));
    rivalTarget = Math.max(wHuman, wBall);
  }
  // Además del peso por distancia, el peso se suaviza en el tiempo: un rival
  // lejano mueve mucho el borde del encuadre aunque el peso cambie poco.
  m.camRival = m.camReady
    ? (m.camRival ?? 0) + (rivalTarget - (m.camRival ?? 0)) * (1 - Math.exp(-RIVAL_WEIGHT_K * safeDt))
    : rivalTarget;
  if (rival && m.camRival > 0.001) {
    minX += (Math.min(minX, rival.x) - minX) * m.camRival;
    maxX += (Math.max(maxX, rival.x) - maxX) * m.camRival;
  }

  const spanX = Math.max(0, maxX - minX);
  const requiredW = clampValue(spanX + CAMERA_MARGIN * 2, minViewW, WORLD.w);

  if (!m.camReady || m.camViewW <= 0) {
    m.camViewW = requiredW;
    m.camReady = true;
  } else {
    // Histéresis: no perseguir variaciones mínimas del borde.
    // Abrir el encuadre es prioritario para no perder la jugada; cerrarlo
    // espera un poco más para que no oscile al rozar el borde.
    const zoomOut = requiredW > m.camViewW + 0.5;
    const zoomIn = requiredW < m.camViewW - CAMERA_HYSTERESIS;
    const targetW = zoomOut || zoomIn ? requiredW : m.camViewW;
    const zoomK = targetW > m.camViewW ? CAMERA_ZOOM_OUT_K : CAMERA_ZOOM_IN_K;

    if (Math.abs(targetW - m.camViewW) > 0.01) {
      m.camViewW += (targetW - m.camViewW) * (1 - Math.exp(-zoomK * safeDt));
    }

    // Red de seguridad: la acción nunca debe quedar fuera mientras el zoom se
    // abre. El margen completo es suave; este mínimo sólo evita el clipping.
    const visibleW = clampValue(spanX + CAMERA_SAFE_MARGIN * 2, minViewW, WORLD.w);
    if (m.camViewW < visibleW) m.camViewW = visibleW;
  }

  m.camViewW = clampValue(m.camViewW, minViewW, WORLD.w);

  // Intervalo de cámara que mantiene a todos los implicados dentro del cuadro.
  let safeW = clampValue(spanX + CAMERA_SAFE_MARGIN * 2, minViewW, WORLD.w);
  if (m.camViewW < safeW) m.camViewW = safeW;
  safeW = m.camViewW;

  const safeMinCamX = Math.max(0, maxX + CAMERA_SAFE_MARGIN - safeW);
  const safeMaxCamX = Math.min(WORLD.w - safeW, minX - CAMERA_SAFE_MARGIN);
  const marginMinCamX = Math.max(0, maxX + CAMERA_MARGIN - safeW);
  const marginMaxCamX = Math.min(WORLD.w - safeW, minX - CAMERA_MARGIN);
  // Límites CONTINUOS. Antes: si el margen completo no cabía se cambiaba de
  // golpe a los límites "seguros" (10 px de margen en vez de CAMERA_MARGIN),
  // y justo al cruzar ese umbral (el rival entrando en cuadro al pasar de la
  // mitad de la cancha) la cámara pegaba un salto de decenas de píxeles.
  // Ahora, si el margen no cabe, los límites colapsan al punto medio (que
  // coincide con ambos en el umbral) y después se encajan en los seguros.
  let minCamX = marginMinCamX;
  let maxCamX = marginMaxCamX;
  if (maxCamX < minCamX) {
    const mid = (minCamX + maxCamX) / 2;
    minCamX = mid;
    maxCamX = mid;
  }
  if (safeMaxCamX >= safeMinCamX) {
    minCamX = clampValue(minCamX, safeMinCamX, safeMaxCamX);
    maxCamX = clampValue(maxCamX, safeMinCamX, safeMaxCamX);
  }
  const worldMaxCamX = Math.max(0, WORLD.w - safeW);
  minCamX = clampValue(minCamX, 0, worldMaxCamX);
  maxCamX = clampValue(maxCamX, 0, worldMaxCamX);
  const contentCenter = (minX + maxX) / 2;
  const weightedFocus = human ? human.x * 0.38 + focusX * 0.62 : focusX;
  const desiredCenter = contentCenter * 0.82 + weightedFocus * 0.18;
  let targetX = clampValue(desiredCenter - safeW / 2, 0, WORLD.w - safeW);
  if (maxCamX >= minCamX) targetX = clampValue(targetX, minCamX, maxCamX);

  // Velocidad de paneo CONSTANTE. Antes saltaba entre 7, 2.7 y 5.8 según el
  // zoom estuviera abriendo, cerrando o quieto, y cada cambio se veía como un
  // tirón de la cámara. Lo que mantiene la jugada dentro es el clamp de abajo.
  const panK = CAMERA_PAN_K;
  if (!Number.isFinite(m.camX) || m.camX < 0) m.camX = targetX;
  else m.camX += (targetX - m.camX) * (1 - Math.exp(-panK * safeDt));

  // Volvemos a limitar tras el suavizado para que ningún frame muestre huecos
  // fuera del mundo ni deje fuera a la pelota.
  m.camX = clampValue(m.camX, 0, Math.max(0, WORLD.w - safeW));
  if (maxCamX >= minCamX) m.camX = clampValue(m.camX, minCamX, maxCamX);

  // El campo completo entra en vertical: y queda anclada y el suelo sigue
  // estable abajo. El zoom uniforme también encoge el eje vertical.
  m.camY = 0;

  const scale = Math.min(canvasW / safeW, canvasH / WORLD.h);
  CAMERA.x = m.camX;
  CAMERA.y = m.camY;
  CAMERA.w = safeW;
  CAMERA.h = WORLD.h;
  CAMERA.scale = scale;
  CAMERA.ox = (canvasW - safeW * scale) / 2;
  // Anclar el mundo abajo deja el cielo extra arriba, nunca debajo del juego.
  CAMERA.oy = canvasH - WORLD.h * scale;
  return CAMERA;
}

function roundRect(
  ctx: CanvasRenderingContext2D,
  x: number,
  y: number,
  w: number,
  h: number,
  r: number,
) {
  const rr = Math.min(r, w / 2, h / 2);
  ctx.beginPath();
  ctx.moveTo(x + rr, y);
  ctx.arcTo(x + w, y, x + w, y + h, rr);
  ctx.arcTo(x + w, y + h, x, y + h, rr);
  ctx.arcTo(x, y + h, x, y, rr);
  ctx.arcTo(x, y, x + w, y, rr);
  ctx.closePath();
}

export function drawMatch(
  ctx: CanvasRenderingContext2D,
  m: Match,
  canvasW: number,
  canvasH: number,
  time: number,
  dt: number,
  reduce: boolean,
  focusControl: "p0" | "p1" = "p0",
) {
  const human = m.fighters.find((f) => f.control === focusControl) ?? m.fighters[0];
  const focus = human ? human.x * 0.45 + m.ball.x * 0.55 : m.ball.x;
  const cam = frameOf(canvasW, canvasH, m, focus, dt, focusControl);
  const mag = reduce ? 0 : m.shake * 8;
  const sx = Math.sin(time * 73) * mag;
  const sy = Math.cos(time * 91) * mag * 0.65;

  ctx.fillStyle = skyGradient(ctx, canvasH);
  ctx.fillRect(0, 0, canvasW, canvasH);
  // En vertical sobra cielo encima del estadio: estrellas y halos de los
  // reflectores (capa cacheada por tamaño de canvas: un drawImage).
  const worldTop = cam.oy - cam.y * cam.scale;
  if (worldTop > 8) {
    const sky = getSkyLayer(canvasW, canvasH);
    if (sky) ctx.drawImage(sky, 0, 0, canvasW, Math.ceil(worldTop), 0, 0, canvasW, Math.ceil(worldTop));
  }

  ctx.save();
  ctx.translate(cam.ox + sx, cam.oy + sy);
  ctx.scale(cam.scale, cam.scale);
  ctx.translate(-cam.x, -cam.y);
  ctx.beginPath();
  ctx.rect(cam.x - 2, cam.y - 2, cam.w + 4, cam.h + 4);
  ctx.clip();

  drawStaticLayer(ctx);
  drawBackdropAnimated(ctx, time, m.phase === "goal" ? 1 : 0);
  drawGoal(ctx, "left", time, m.fighters[0]?.name ?? "SOL", m);
  drawGoal(ctx, "right", time, m.fighters[1]?.name ?? "LUNA", m);
  drawPowerup(ctx, m, time);

  drawShadow(ctx, m.ball.x, m.ball.r * 0.85);
  for (const f of m.fighters) {
    // La sombra se encoge con la altura: ancla al luchador al suelo (2.5D).
    const lift = Math.max(0, WORLD.ground - (f.y + 34));
    drawShadow(ctx, f.x, (17 + Math.abs(f.vx) * 0.01) * Math.max(0.45, 1 - lift / 320));
  }
  drawBall(ctx, m.ball, m.sudden);
  // The ball is behind the front of the net once it is inside the pocket:
  // redraw the mesh of that goal over the ball so it reads as caught, not
  // pasted on top.
  if (m.phase === "goal") {
    const left = m.ball.x < WORLD.w / 2;
    const mouthX = left ? WORLD.mouth : WORLD.w - WORLD.mouth;
    const backX = left ? WORLD.back : WORLD.w - WORLD.back;
    drawNetMesh(
      ctx,
      Math.min(mouthX, backX),
      Math.abs(mouthX - backX),
      WORLD.goalTop,
      WORLD.goalBottom,
      left,
      time,
      netBulge(m, left),
      0.5,
    );
  }
  // 1v1: two fighters only. Avoid array allocation/sort every frame.
  const f0 = m.fighters[0];
  const f1 = m.fighters[1];
  const scoringTeam =
    m.phase === "goal" ? (m.ball.x < WORLD.w / 2 ? "right" : "left") : null;
  const winningTeam =
    m.phase === "over" ? (m.scoreL >= m.scoreR ? "left" : "right") : null;
  if (f0 && f1) {
    if (f0.y <= f1.y) {
      drawFighter(ctx, f0, m.ball, time, moodFor(f0, scoringTeam, winningTeam));
      drawFighter(ctx, f1, m.ball, time, moodFor(f1, scoringTeam, winningTeam));
    } else {
      drawFighter(ctx, f1, m.ball, time, moodFor(f1, scoringTeam, winningTeam));
      drawFighter(ctx, f0, m.ball, time, moodFor(f0, scoringTeam, winningTeam));
    }
  } else if (f0) {
    drawFighter(ctx, f0, m.ball, time, moodFor(f0, scoringTeam, winningTeam));
  }
  drawPosts(ctx);
  for (const p of m.particles) drawParticle(ctx, p);
  drawGoalCelebration(ctx, m, time);
  for (const t of m.texts) drawFloat(ctx, t);

  if (m.phase === "goal") {
    ctx.save();
    ctx.textAlign = "center";
    ctx.fillStyle = "rgba(7, 20, 16, 0.35)";
    ctx.fillRect(cam.x, 168, cam.w, 120);
    // The banner pops in big and settles: it scales with the goal timer.
    const pop = 1 + 0.45 * Math.max(0, (m.timer - 1.45) / 0.25);
    ctx.translate(cam.x + cam.w / 2, 230);
    ctx.scale(pop, pop);
    ctx.fillStyle = "#ffb703";
    ctx.font = '800 64px "Lilita One", "Arial Black", sans-serif';
    ctx.fillText(m.banner, 0, 0);
    if (m.subtitle) {
      ctx.fillStyle = "#f6efe2";
      ctx.font = '700 22px "Outfit", system-ui, sans-serif';
      ctx.fillText(m.subtitle, 0, 34);
    }
    ctx.restore();
  }

  ctx.restore();
  drawOffscreen(ctx, m, cam);
}

// Static background layer, prerendered once at 2x world resolution and
// blitted every frame. The world is a fixed size, so it never invalidates.
// Only the truly static shapes live here (trees, stands, beams, pitch);
// spectators, lanterns and goal nets animate, so they stay dynamic.
// Falls back to drawing the static shapes directly when there is no DOM
// (SSR) or the offscreen canvas cannot be created.
const STATIC_SCALE = 2;
let staticLayer: HTMLCanvasElement | null = null;
let fontsHooked = false;

function getStaticLayer(): HTMLCanvasElement | null {
  if (typeof document === "undefined") return null;
  if (staticLayer) return staticLayer;
  const c = document.createElement("canvas");
  c.width = WORLD.w * STATIC_SCALE;
  c.height = WORLD.h * STATIC_SCALE;
  const off = c.getContext("2d");
  if (!off) return null;
  off.scale(STATIC_SCALE, STATIC_SCALE);
  drawBackdropStatic(off);
  drawPitch(off);
  staticLayer = c;
  // Las vallas usan Lilita One: si la fuente aún no cargó, repintar el fondo
  // cuando llegue (una sola vez) para no quedarse con la letra de reserva.
  if (!fontsHooked && document.fonts && document.fonts.status !== "loaded") {
    fontsHooked = true;
    void document.fonts.ready.then(() => invalidateStaticLayer());
  }
  return c;
}

function drawStaticLayer(ctx: CanvasRenderingContext2D) {
  const layer = getStaticLayer();
  if (layer) {
    ctx.drawImage(layer, 0, 0, WORLD.w, WORLD.h);
    return;
  }
  drawBackdropStatic(ctx);
  drawPitch(ctx);
}

/**
 * Forzar que el fondo estático se vuelva a dibujar. El móvil puede borrar
 * el canvas guardado cuando la pestaña pasa a segundo plano (al compartir
 * por WhatsApp); sin esto el escenario queda incompleto al volver.
 */
export function invalidateStaticLayer(): void {
  staticLayer = null;
  labelWidthCache.clear();
}

// Gradiente del cielo, creado una sola vez por tamaño de canvas en vez de
// en cada frame (era una asignación por frame en el camino caliente).
let skyGrad: { ctx: CanvasRenderingContext2D; h: number; grad: CanvasGradient } | null = null;

let skyLayer: { w: number; h: number; c: HTMLCanvasElement } | null = null;

function getSkyLayer(w: number, h: number): HTMLCanvasElement | null {
  if (typeof document === "undefined") return null;
  if (skyLayer && skyLayer.w === w && skyLayer.h === h) return skyLayer.c;
  const c = document.createElement("canvas");
  c.width = w;
  c.height = h;
  const g = c.getContext("2d");
  if (!g) return null;
  const rand = texRand(4242);
  const unit = Math.max(1, w / 400);
  for (let i = 0; i < 90; i++) {
    const x = rand() * w;
    const y = rand() * h * 0.7;
    const r = (0.6 + rand() * 1.3) * unit;
    g.fillStyle = `rgba(255, 248, 225, ${0.25 + rand() * 0.55})`;
    g.beginPath();
    g.arc(x, y, r, 0, Math.PI * 2);
    g.fill();
  }
  // Halos de dos torres de luz lejanas.
  for (const fx of [0.12, 0.88]) {
    const grad = g.createRadialGradient(w * fx, h * 0.18, 0, w * fx, h * 0.18, w * 0.45);
    grad.addColorStop(0, "rgba(255, 236, 170, 0.20)");
    grad.addColorStop(1, "rgba(255, 236, 170, 0)");
    g.fillStyle = grad;
    g.fillRect(0, 0, w, h);
    g.fillStyle = "#0a1712";
    g.fillRect(w * fx - 3 * unit, h * 0.18, 6 * unit, h);
    g.fillStyle = "#fff4cf";
    for (let k = 0; k < 3; k++) {
      g.beginPath();
      g.arc(w * fx + (k - 1) * 9 * unit, h * 0.18, 3.5 * unit, 0, Math.PI * 2);
      g.fill();
    }
  }
  skyLayer = { w, h, c };
  return c;
}

function skyGradient(ctx: CanvasRenderingContext2D, canvasH: number): CanvasGradient {
  if (skyGrad && skyGrad.ctx === ctx && skyGrad.h === canvasH) return skyGrad.grad;
  const grad = ctx.createLinearGradient(0, 0, 0, canvasH);
  grad.addColorStop(0, "#07140f");
  grad.addColorStop(0.45, "#12382c");
  grad.addColorStop(1, "#1d4a32");
  skyGrad = { ctx, h: canvasH, grad };
  return grad;
}

/* ------------------------------------------------------------------ */
/* Estadio (primera cancha). Todo lo pesado va al fondo estático, que  */
/* se pinta UNA vez a 2x y luego es un solo drawImage por frame.       */
/* ------------------------------------------------------------------ */

/** Pseudo-aleatorio fijo para texturas: mismo estadio en cada carga. */
function texRand(seed: number): () => number {
  let a = seed >>> 0;
  return () => {
    a = (a + 0x6d2b79f5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

const STAND_TOP = 78;
const TURF_FAR = 486;
const BOARD_TOP = 456;
const BOARD_BOTTOM = TURF_FAR;
const SEAT_ROWS = [118, 148, 178] as const;

function drawBackdropStatic(ctx: CanvasRenderingContext2D) {
  const W = WORLD.w;
  const standBottom = WORLD.standBottom;

  // --- Cercha del techo (es el techo físico: la pelota rebota en y = 30) ---
  ctx.fillStyle = "#1b2b2c";
  ctx.fillRect(0, 14, W, 22);
  ctx.fillStyle = "#2c4442";
  ctx.fillRect(0, 14, W, 4);
  ctx.fillStyle = "#0e1a1a";
  ctx.fillRect(0, 32, W, 4);
  ctx.strokeStyle = "#35514d";
  ctx.lineWidth = 2;
  ctx.beginPath();
  for (let x = 0; x < W; x += 40) {
    ctx.moveTo(x, 18);
    ctx.lineTo(x + 20, 32);
    ctx.lineTo(x + 40, 18);
  }
  ctx.stroke();

  // --- Reflectores colgantes y sus haces de luz ---
  for (let i = 0; i < 4; i++) {
    const x = 170 + i * 233;
    ctx.fillStyle = "rgba(255, 236, 170, 0.07)";
    ctx.beginPath();
    ctx.moveTo(x - 18, 56);
    ctx.lineTo(x + 18, 56);
    ctx.lineTo(x + 150, TURF_FAR);
    ctx.lineTo(x - 150, TURF_FAR);
    ctx.closePath();
    ctx.fill();
    ctx.fillStyle = "#1b2b2c";
    ctx.fillRect(x - 2, 36, 4, 10);
    roundRect(ctx, x - 24, 44, 48, 14, 5);
    ctx.fillStyle = "#25393a";
    ctx.fill();
    ctx.strokeStyle = "#0b1414";
    ctx.lineWidth = 2;
    ctx.stroke();
    ctx.fillStyle = "#fff4cf";
    for (let k = 0; k < 3; k++) {
      ctx.beginPath();
      ctx.arc(x - 14 + k * 14, 53, 4.2, 0, Math.PI * 2);
      ctx.fill();
    }
    ctx.fillStyle = "rgba(255, 236, 170, 0.22)";
    ctx.beginPath();
    ctx.ellipse(x, 58, 34, 9, 0, 0, Math.PI * 2);
    ctx.fill();
  }

  // --- Muro de fondo bajo la grada (con haces de luz y paneles) ---
  const wall = ctx.createLinearGradient(0, standBottom, 0, TURF_FAR);
  wall.addColorStop(0, "#0b231b");
  wall.addColorStop(0.6, "#123527");
  wall.addColorStop(1, "#18432f");
  ctx.fillStyle = wall;
  ctx.fillRect(0, standBottom, W, TURF_FAR - standBottom);
  ctx.strokeStyle = "rgba(255,255,255,0.035)";
  ctx.lineWidth = 2;
  ctx.beginPath();
  for (let x = 52; x < W; x += 104) {
    ctx.moveTo(x, standBottom);
    ctx.lineTo(x, BOARD_TOP);
  }
  ctx.stroke();
  // Banderines de los dos equipos colgando de la baranda.
  for (let i = 0; i < 12; i++) {
    const x = 110 + i * 74;
    const left = x < W / 2;
    ctx.fillStyle = left ? "#ff5a36" : "#3d8bfd";
    ctx.beginPath();
    ctx.moveTo(x - 14, standBottom + 2);
    ctx.lineTo(x + 14, standBottom + 2);
    ctx.lineTo(x, standBottom + 30);
    ctx.closePath();
    ctx.fill();
    ctx.fillStyle = "rgba(0,0,0,0.22)";
    ctx.beginPath();
    ctx.moveTo(x, standBottom + 2);
    ctx.lineTo(x + 14, standBottom + 2);
    ctx.lineTo(x, standBottom + 30);
    ctx.closePath();
    ctx.fill();
  }

  // --- Grada: techo, escalones y asientos de colores ---
  ctx.fillStyle = "#3b2414";
  roundRect(ctx, 20, STAND_TOP, W - 40, standBottom - STAND_TOP, 14);
  ctx.fill();
  ctx.fillStyle = "#24160c";
  ctx.fillRect(20, STAND_TOP, W - 40, 12);
  const seatColors = ["#c8462c", "#e0a12a", "#2f6fc4"];
  SEAT_ROWS.forEach((y, row) => {
    // Escalón de madera con canto iluminado.
    ctx.fillStyle = row % 2 === 0 ? "#5a361d" : "#51301a";
    ctx.fillRect(28, y - 4, W - 56, 30);
    ctx.fillStyle = "#7a4a26";
    ctx.fillRect(28, y + 22, W - 56, 3);
    ctx.fillStyle = "rgba(0,0,0,0.25)";
    ctx.fillRect(28, y + 25, W - 56, 3);
    // Respaldos de asiento.
    ctx.fillStyle = seatColors[row];
    for (let x = 52; x < W - 40; x += 34) {
      roundRect(ctx, x, y + 8, 22, 12, 4);
      ctx.fill();
    }
  });
  // Baranda frontal.
  ctx.fillStyle = "#24160c";
  ctx.fillRect(20, standBottom - 14, W - 40, 14);
  ctx.strokeStyle = "#c9d6cf";
  ctx.lineWidth = 3;
  ctx.beginPath();
  ctx.moveTo(24, standBottom - 16);
  ctx.lineTo(W - 24, standBottom - 16);
  ctx.stroke();
  ctx.lineWidth = 2;
  ctx.beginPath();
  for (let x = 40; x < W - 20; x += 40) {
    ctx.moveTo(x, standBottom - 16);
    ctx.lineTo(x, standBottom - 2);
  }
  ctx.stroke();

  // --- Grada baja en penumbra (segundo plano: da profundidad 2.5D) ---
  const sil = texRand(77);
  ctx.fillStyle = "#081a13";
  ctx.fillRect(0, BOARD_TOP - 34, W, 34);
  for (let row = 0; row < 2; row++) {
    ctx.fillStyle = row === 0 ? "#0c241a" : "#0f2c20";
    ctx.beginPath();
    for (let x = 6 + row * 11; x < W; x += 22) {
      const y = BOARD_TOP - 24 + row * 12 + sil() * 3;
      ctx.moveTo(x + 7, y);
      ctx.arc(x, y, 7, 0, Math.PI * 2);
      ctx.moveTo(x + 11, y + 14);
      ctx.ellipse(x, y + 14, 11, 8, 0, Math.PI, 0);
    }
    ctx.fill();
  }

  // --- Vallas publicitarias LED detrás de la cancha ---
  ctx.fillStyle = "#0a1210";
  ctx.fillRect(WORLD.mouth, BOARD_TOP - 4, W - WORLD.mouth * 2, BOARD_BOTTOM - BOARD_TOP + 4);
  const boards: [string, string, string][] = [
    ["#ffb703", "#3a2500", "GOAL FIGHTERS"],
    ["#ff5a36", "#fff8e8", "FUTGOGOS"],
    ["#3d8bfd", "#fff8e8", "¡GOOOL!"],
    ["#7ada4a", "#10241c", "1 VS 1"],
  ];
  const bw = (W - WORLD.mouth * 2 - 8) / 6;
  ctx.font = '22px "Lilita One", "Arial Black", sans-serif';
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  for (let i = 0; i < 6; i++) {
    const [bg, fg, text] = boards[i % boards.length];
    const x = WORLD.mouth + 4 + i * bw;
    ctx.fillStyle = bg;
    ctx.fillRect(x + 2, BOARD_TOP, bw - 4, BOARD_BOTTOM - BOARD_TOP - 4);
    ctx.fillStyle = "rgba(255,255,255,0.16)";
    ctx.fillRect(x + 2, BOARD_TOP, bw - 4, 7);
    ctx.fillStyle = fg;
    // Si el texto no cabe en la valla, se reduce (solo se pinta una vez).
    const tw = ctx.measureText(text).width;
    const fit = Math.min(1, (bw - 14) / tw);
    ctx.save();
    ctx.translate(x + bw / 2, (BOARD_TOP + BOARD_BOTTOM) / 2);
    ctx.scale(fit, fit);
    ctx.fillText(text, 0, 0);
    ctx.restore();
  }
  // Retícula de LEDs.
  ctx.fillStyle = "rgba(0,0,0,0.16)";
  for (let y = BOARD_TOP + 3; y < BOARD_BOTTOM - 4; y += 4) ctx.fillRect(WORLD.mouth, y, W - WORLD.mouth * 2, 1);
  // Atenuadas: están justo detrás de las cabezas y no deben competir con los luchadores.
  ctx.fillStyle = "rgba(6, 18, 14, 0.34)";
  ctx.fillRect(WORLD.mouth, BOARD_TOP - 4, W - WORLD.mouth * 2, BOARD_BOTTOM - BOARD_TOP + 4);
  ctx.textBaseline = "alphabetic";
}

/** Gente de la grada: cuerpo y cabeza por color, en lotes (pocos fill por frame). */
const CROWD_SHIRTS = ["#ff5a36", "#ffb703", "#3d8bfd", "#f6efe2", "#7CDA4A"];
const CROWD_SKIN = ["#f0b47d", "#a86a45", "#ffd7c7"];
const CROWD_N = 42;

function crowdPos(i: number, time: number, excite: number) {
  const x = 66 + (i % 14) * 68 + ((i * 37) % 11) - 5;
  const row = Math.floor(i / 14);
  const amp = 1.4 + excite * 6;
  const y = SEAT_ROWS[row] + 2 + Math.sin(time * (3 + excite * 6) + i * 1.7) * amp;
  return { x, y };
}

function drawBackdropAnimated(ctx: CanvasRenderingContext2D, time: number, excite = 0) {
  for (let c = 0; c < CROWD_SHIRTS.length; c++) {
    ctx.fillStyle = CROWD_SHIRTS[c];
    ctx.beginPath();
    for (let i = c; i < CROWD_N; i += CROWD_SHIRTS.length) {
      const { x, y } = crowdPos(i, time, excite);
      ctx.moveTo(x + 11, y + 14);
      ctx.ellipse(x, y + 14, 11, 8, 0, Math.PI, 0);
    }
    ctx.fill();
  }
  for (let c = 0; c < CROWD_SKIN.length; c++) {
    ctx.fillStyle = CROWD_SKIN[c];
    ctx.beginPath();
    for (let i = c; i < CROWD_N; i += CROWD_SKIN.length) {
      const { x, y } = crowdPos(i, time, excite);
      ctx.moveTo(x + 7.5, y);
      ctx.arc(x, y, 7.5, 0, Math.PI * 2);
    }
    ctx.fill();
  }
  // Brazos arriba al celebrar.
  if (excite > 0.05) {
    ctx.strokeStyle = "#f0b47d";
    ctx.lineWidth = 3;
    ctx.lineCap = "round";
    ctx.beginPath();
    for (let i = 0; i < CROWD_N; i += 2) {
      const { x, y } = crowdPos(i, time, excite);
      const wave = Math.sin(time * 10 + i) * 3;
      ctx.moveTo(x - 9, y + 10);
      ctx.lineTo(x - 13 + wave, y - 8);
      ctx.moveTo(x + 9, y + 10);
      ctx.lineTo(x + 13 - wave, y - 8);
    }
    ctx.stroke();
  }
}

function drawPitch(ctx: CanvasRenderingContext2D) {
  const W = WORLD.w;
  const g = WORLD.ground;
  const rand = texRand(20261114);

  // --- Cara frontal: corte de tierra con estratos, piedras y raíces ---
  ctx.fillStyle = "#5b331c";
  ctx.fillRect(0, g, W, WORLD.h - g);
  ctx.fillStyle = "#4a2914";
  ctx.fillRect(0, g + 26, W, WORLD.h - g - 26);
  ctx.fillStyle = "#3b200f";
  ctx.fillRect(0, g + 44, W, WORLD.h - g - 44);
  ctx.strokeStyle = "rgba(255, 210, 160, 0.08)";
  ctx.lineWidth = 2;
  ctx.beginPath();
  for (let x = 0; x < W; x += 6) {
    const y = g + 24 + Math.sin(x * 0.03) * 2.5;
    if (x === 0) ctx.moveTo(x, y);
    else ctx.lineTo(x, y);
  }
  ctx.stroke();
  for (let i = 0; i < 70; i++) {
    const x = rand() * W;
    const y = g + 12 + rand() * (WORLD.h - g - 14);
    const r = 2 + rand() * 4.5;
    ctx.fillStyle = rand() < 0.5 ? "#6e4529" : "#2f190b";
    ctx.beginPath();
    ctx.ellipse(x, y, r * 1.4, r, rand() * Math.PI, 0, Math.PI * 2);
    ctx.fill();
    ctx.fillStyle = "rgba(255,230,190,0.18)";
    ctx.beginPath();
    ctx.ellipse(x - r * 0.4, y - r * 0.4, r * 0.5, r * 0.3, 0, 0, Math.PI * 2);
    ctx.fill();
  }
  ctx.strokeStyle = "#2a160a";
  ctx.lineWidth = 2;
  ctx.lineCap = "round";
  ctx.beginPath();
  for (let i = 0; i < 14; i++) {
    let x = rand() * W;
    let y = g + 8;
    ctx.moveTo(x, y);
    for (let k = 0; k < 3; k++) {
      x += (rand() - 0.5) * 16;
      y += 6 + rand() * 7;
      ctx.lineTo(x, y);
    }
  }
  ctx.stroke();

  // --- Superficie del césped en perspectiva (franjas de corte) ---
  const turfL = WORLD.mouth;
  const turfR = W - WORLD.mouth;
  ctx.save();
  ctx.beginPath();
  ctx.rect(turfL, TURF_FAR, turfR - turfL, g - TURF_FAR + 1);
  ctx.clip();
  ctx.fillStyle = "#3f9a3e";
  ctx.fillRect(turfL, TURF_FAR, turfR - turfL, g - TURF_FAR + 1);
  const band = 58;
  for (let i = -2; i < (turfR - turfL) / band + 2; i++) {
    if (i % 2 !== 0) continue;
    const x = turfL + i * band;
    // Paralelogramo: el borde lejano va desplazado hacia el centro (punto de fuga).
    const skewFar = (x + band / 2 - W / 2) * -0.12;
    ctx.fillStyle = "#4daa48";
    ctx.beginPath();
    ctx.moveTo(x, g + 1);
    ctx.lineTo(x + band, g + 1);
    ctx.lineTo(x + band + skewFar, TURF_FAR);
    ctx.lineTo(x + skewFar, TURF_FAR);
    ctx.closePath();
    ctx.fill();
  }
  // Brillo del reflector sobre el césped y sombra hacia el fondo.
  ctx.fillStyle = "rgba(0, 30, 10, 0.22)";
  ctx.fillRect(turfL, TURF_FAR, turfR - turfL, 7);
  // Hierba: trazos cortos.
  ctx.strokeStyle = "rgba(190, 255, 150, 0.28)";
  ctx.lineWidth = 1.2;
  ctx.beginPath();
  for (let i = 0; i < 420; i++) {
    const x = turfL + rand() * (turfR - turfL);
    const y = TURF_FAR + 6 + rand() * (g - TURF_FAR - 6);
    ctx.moveTo(x, y);
    ctx.lineTo(x + (rand() - 0.5) * 3, y - 3 - rand() * 3);
  }
  ctx.stroke();
  // Líneas pintadas: banda lejana, banda cercana, línea media y círculo central.
  ctx.strokeStyle = "rgba(246, 239, 226, 0.75)";
  ctx.lineWidth = 2.5;
  ctx.beginPath();
  ctx.moveTo(turfL + 14, TURF_FAR + 9);
  ctx.lineTo(turfR - 14, TURF_FAR + 9);
  ctx.moveTo(turfL + 4, g - 3);
  ctx.lineTo(turfR - 4, g - 3);
  ctx.moveTo(W / 2, TURF_FAR + 9);
  ctx.lineTo(W / 2, g - 3);
  ctx.stroke();
  ctx.beginPath();
  ctx.ellipse(W / 2, (TURF_FAR + 9 + g - 3) / 2, 78, (g - 3 - TURF_FAR - 9) / 2, 0, 0, Math.PI * 2);
  ctx.stroke();
  ctx.fillStyle = "rgba(246, 239, 226, 0.85)";
  ctx.beginPath();
  ctx.ellipse(W / 2, (TURF_FAR + 9 + g - 3) / 2, 4, 1.8, 0, 0, Math.PI * 2);
  ctx.fill();
  // Áreas junto a cada portería.
  ctx.beginPath();
  ctx.moveTo(turfL + 4, TURF_FAR + 12);
  ctx.lineTo(turfL + 120, TURF_FAR + 12);
  ctx.lineTo(turfL + 132, g - 3);
  ctx.moveTo(turfR - 4, TURF_FAR + 12);
  ctx.lineTo(turfR - 120, TURF_FAR + 12);
  ctx.lineTo(turfR - 132, g - 3);
  ctx.stroke();
  ctx.restore();

  // --- Borde del césped: labio verde con mechones que cuelgan sobre la tierra ---
  ctx.fillStyle = "#2f7d33";
  ctx.fillRect(0, g, W, 7);
  ctx.fillStyle = "#3f9a3e";
  ctx.beginPath();
  ctx.moveTo(0, g + 6);
  for (let x = 0; x <= W; x += 9) {
    ctx.lineTo(x + 4.5, g + 9 + rand() * 6);
    ctx.lineTo(x + 9, g + 6);
  }
  ctx.lineTo(W, g);
  ctx.lineTo(0, g);
  ctx.closePath();
  ctx.fill();
  ctx.fillStyle = "rgba(210, 255, 170, 0.35)";
  ctx.fillRect(0, g, W, 2);

  // --- Portería: muro, bolsillo con profundidad y pedestal (parte fija) ---
  drawGoalStatic(ctx, "left");
  drawGoalStatic(ctx, "right");
}

/**
 * Parte fija de cada portería: el muro lateral, el hueco de la ventana con
 * sus caras interiores en perspectiva (techo, suelo y fondo) y el pedestal
 * de ladrillo con el escudo del equipo. Va al fondo estático: cero coste por frame.
 */
function drawGoalStatic(ctx: CanvasRenderingContext2D, side: "left" | "right") {
  const left = side === "left";
  const mouthX = left ? WORLD.mouth : WORLD.w - WORLD.mouth;
  const backX = left ? WORLD.back : WORLD.w - WORLD.back;
  const x0 = Math.min(mouthX, backX);
  const width = Math.abs(mouthX - backX);
  const top = WORLD.goalTop;
  const bottom = WORLD.goalBottom;
  const color = left ? "#ff5a36" : "#3d8bfd";
  const dark = left ? "#8a2614" : "#183f86";
  const wallX = left ? 0 : WORLD.w - WORLD.back;

  // Muro lateral completo (de la grada al suelo) detrás del pedestal.
  ctx.fillStyle = "#2b1a10";
  ctx.fillRect(left ? 0 : x0, WORLD.standBottom, (left ? x0 : WORLD.w - x0) + width, WORLD.ground - WORLD.standBottom);
  ctx.fillStyle = "#1c110a";
  ctx.fillRect(wallX, WORLD.standBottom, WORLD.back, WORLD.ground - WORLD.standBottom);

  // Dintel sobre la ventana.
  ctx.fillStyle = "#3b2517";
  ctx.fillRect(x0, WORLD.standBottom, width, top - WORLD.standBottom);
  ctx.fillStyle = color;
  ctx.fillRect(x0, top - 12, width, 5);

  // Hueco: fondo oscuro + caras interiores en perspectiva.
  const depth = 16;
  const backL = left ? x0 : x0 + depth;
  const backR = left ? x0 + width - depth : x0 + width;
  ctx.fillStyle = "#06120e";
  ctx.fillRect(x0, top, width, bottom - top);
  // Fondo (pared trasera) un poco más claro y más pequeño.
  ctx.fillStyle = "#0f2a20";
  ctx.fillRect(backL, top + depth * 0.7, backR - backL, bottom - top - depth * 1.4);
  // Techo interior.
  ctx.fillStyle = "#1c3a2e";
  ctx.beginPath();
  ctx.moveTo(x0, top);
  ctx.lineTo(x0 + width, top);
  ctx.lineTo(backR, top + depth * 0.7);
  ctx.lineTo(backL, top + depth * 0.7);
  ctx.closePath();
  ctx.fill();
  // Suelo interior (iluminado).
  ctx.fillStyle = "#2d5a40";
  ctx.beginPath();
  ctx.moveTo(x0, bottom);
  ctx.lineTo(x0 + width, bottom);
  ctx.lineTo(backR, bottom - depth * 0.7);
  ctx.lineTo(backL, bottom - depth * 0.7);
  ctx.closePath();
  ctx.fill();
  // Resplandor del color del equipo desde la boca.
  const glow = ctx.createLinearGradient(left ? mouthX : mouthX - 30, 0, left ? mouthX - 30 : mouthX, 0);
  glow.addColorStop(0, left ? "rgba(255,90,54,0.28)" : "rgba(61,139,253,0.28)");
  glow.addColorStop(1, "rgba(0,0,0,0)");
  ctx.fillStyle = glow;
  ctx.fillRect(x0, top, width, bottom - top);

  // Pedestal de ladrillo bajo la ventana.
  const pTop = bottom;
  ctx.fillStyle = "#5a321b";
  ctx.fillRect(x0, pTop, width, WORLD.ground - pTop);
  ctx.strokeStyle = "rgba(0,0,0,0.3)";
  ctx.lineWidth = 2;
  ctx.beginPath();
  for (let y = pTop + 14, row = 0; y < WORLD.ground; y += 14, row++) {
    ctx.moveTo(x0, y);
    ctx.lineTo(x0 + width, y);
    for (let x = x0 + (row % 2 ? 10 : 26); x < x0 + width; x += 32) {
      ctx.moveTo(x, y - 14);
      ctx.lineTo(x, y);
    }
  }
  ctx.stroke();
  // Canto iluminado del lado de la cancha.
  ctx.fillStyle = "rgba(255, 220, 170, 0.16)";
  ctx.fillRect(left ? mouthX - 5 : mouthX, pTop + 6, 5, WORLD.ground - pTop - 6);
  // Acolchado con el color del equipo y escudo.
  ctx.fillStyle = color;
  ctx.fillRect(x0, pTop + 8, width, 10);
  ctx.fillStyle = dark;
  ctx.fillRect(x0, pTop + 15, width, 3);
  const cx = x0 + width / 2;
  const cy = pTop + 62;
  ctx.fillStyle = "#f4efe4";
  ctx.beginPath();
  ctx.moveTo(cx - 17, cy - 18);
  ctx.lineTo(cx + 17, cy - 18);
  ctx.lineTo(cx + 15, cy + 6);
  ctx.quadraticCurveTo(cx, cy + 22, cx - 15, cy + 6);
  ctx.closePath();
  ctx.fill();
  ctx.strokeStyle = "#21151f";
  ctx.lineWidth = 2.5;
  ctx.stroke();
  ctx.fillStyle = color;
  ctx.beginPath();
  ctx.arc(cx, cy - 2, 9, 0, Math.PI * 2);
  ctx.fill();
  ctx.fillStyle = "#21151f";
  ctx.beginPath();
  ctx.arc(cx, cy - 2, 3.5, 0, Math.PI * 2);
  ctx.fill();
  // Sombra del pedestal sobre el césped.
  ctx.fillStyle = "rgba(0,0,0,0.25)";
  ctx.beginPath();
  ctx.ellipse(mouthX + (left ? 10 : -10), WORLD.ground - 4, 26, 6, 0, 0, Math.PI * 2);
  ctx.fill();
}

type NetBulge = { amount: number; y: number };

/**
 * How far the net is pushed out by the ball: 0 in normal play, up to ~1.25
 * while the ball rests against the back of the net. Pure function of the
 * ball, so no extra state and no sync risk.
 */
function netBulge(m: Match, left: boolean): NetBulge {
  if (m.phase !== "goal") return { amount: 0, y: 0 };
  const b = m.ball;
  if ((b.x < WORLD.w / 2) !== left) return { amount: 0, y: 0 };
  const mouthX = left ? WORLD.mouth : WORLD.w - WORLD.mouth;
  const backX = left ? WORLD.back : WORLD.w - WORLD.back;
  const depth = Math.abs(mouthX - backX);
  const pen = Math.min(1, Math.abs(mouthX - b.x) / depth);
  const speed = Math.min(0.5, Math.hypot(b.vx, b.vy) / 1400);
  return { amount: Math.min(1.25, pen * 0.85 + speed), y: b.y };
}

function drawNetMesh(
  ctx: CanvasRenderingContext2D,
  x0: number,
  width: number,
  top: number,
  bottom: number,
  left: boolean,
  time: number,
  bulge: NetBulge,
  alpha: number,
) {
  // Red de rombos, recortada a la ventana para que nunca se salga.
  ctx.save();
  ctx.beginPath();
  ctx.rect(x0 + 2, top + 2, width - 4, bottom - top - 4);
  ctx.clip();
  ctx.strokeStyle = `rgba(240, 236, 226, ${0.5 * alpha})`;
  ctx.lineWidth = 1.5;
  const wob = Math.sin(time * 6) * 1.2;
  const out = left ? -1 : 1; // hacia fuera = alejándose del campo
  const bulgePx = bulge.amount * 14;
  const midY = (top + bottom) / 2;
  const gauss = (y: number) => Math.exp(-((y - bulge.y) * (y - bulge.y)) / (2 * 45 * 45));
  const push = out * bulgePx * gauss(midY);
  const h = bottom - top;
  const step = 16;
  // Dos familias de diagonales en un solo trazado: un único stroke().
  ctx.beginPath();
  for (let k = -h; k < width + h; k += step) {
    ctx.moveTo(x0 + k, top);
    ctx.quadraticCurveTo(x0 + k + h / 2 + push, midY + wob, x0 + k + h, bottom);
    ctx.moveTo(x0 + k + h, top);
    ctx.quadraticCurveTo(x0 + k + h / 2 + push, midY - wob, x0 + k, bottom);
  }
  ctx.stroke();
  // Sombra de la red sobre el fondo del hueco (da volumen).
  ctx.strokeStyle = `rgba(0, 0, 0, ${0.25 * alpha})`;
  ctx.lineWidth = 3;
  ctx.beginPath();
  ctx.moveTo(x0, top + 3);
  ctx.lineTo(x0 + width, top + 3);
  ctx.stroke();
  ctx.restore();
}

// measureText cada frame obliga a resolver la fuente; el ancho del nombre
// solo cambia cuando cambia el personaje.
const labelWidthCache = new Map<string, number>();

function labelWidth(ctx: CanvasRenderingContext2D, text: string): number {
  const hit = labelWidthCache.get(text);
  if (hit !== undefined) return hit;
  const w = ctx.measureText(text).width;
  if (labelWidthCache.size > 40) labelWidthCache.clear();
  labelWidthCache.set(text, w);
  return w;
}

function drawGoal(ctx: CanvasRenderingContext2D, side: "left" | "right", time: number, teamName: string, m: Match) {
  const left = side === "left";
  const mouthX = left ? WORLD.mouth : WORLD.w - WORLD.mouth;
  const backX = left ? WORLD.back : WORLD.w - WORLD.back;
  const x0 = Math.min(mouthX, backX);
  const width = Math.abs(mouthX - backX);
  const top = WORLD.goalTop;
  const bottom = WORLD.goalBottom;
  const color = left ? "#ff5a36" : "#3d8bfd";

  // Muro, hueco y pedestal están en el fondo estático; aquí solo lo que se mueve.
  drawNetMesh(ctx, x0, width, top, bottom, left, time, netBulge(m, left), 1);

  // Nombre del equipo dentro de la red, justo debajo del larguero.
  const nameX = left ? (WORLD.back + WORLD.mouth) / 2 : WORLD.w - (WORLD.back + WORLD.mouth) / 2;
  ctx.font = '800 15px "Outfit", system-ui, sans-serif';
  ctx.textAlign = "center";
  const nameWidth = labelWidth(ctx, teamName.toUpperCase());
  ctx.fillStyle = "rgba(7, 18, 15, 0.8)";
  roundRect(ctx, nameX - nameWidth / 2 - 5, top + 10, nameWidth + 10, 20, 6);
  ctx.fill();
  ctx.fillStyle = color;
  ctx.fillText(teamName.toUpperCase(), nameX, top + 24);
}

function drawPosts(ctx: CanvasRenderingContext2D) {
  // Larguero y travesaño inferior como tubos: base clara, sombra abajo,
  // brillo arriba y bandas del color del equipo.
  const bar = (x: number, y: number, w: number, alignTop: boolean, color: string) => {
    const by = alignTop ? y : y - 6;
    roundRect(ctx, x, by, w, 12, 6);
    ctx.fillStyle = "#f4efe4";
    ctx.fill();
    ctx.save();
    ctx.clip();
    ctx.fillStyle = "#c9bfa9";
    ctx.fillRect(x, by + 7, w, 5);
    ctx.fillStyle = color;
    for (let bx = x + 8; bx < x + w - 4; bx += 18) ctx.fillRect(bx, by, 7, 12);
    ctx.fillStyle = "rgba(0,0,0,0.18)";
    ctx.fillRect(x, by + 8, w, 4);
    ctx.fillStyle = "rgba(255,255,255,0.75)";
    ctx.fillRect(x, by + 2, w, 2);
    ctx.restore();
    roundRect(ctx, x, by, w, 12, 6);
    ctx.strokeStyle = "#21151f";
    ctx.lineWidth = 2;
    ctx.stroke();
  };
  const L = "#ff5a36";
  const R = "#3d8bfd";
  bar(WORLD.back, WORLD.goalTop, WORLD.mouth - WORLD.back, true, L);
  bar(WORLD.w - WORLD.mouth, WORLD.goalTop, WORLD.mouth - WORLD.back, true, R);
  bar(WORLD.back, WORLD.goalBottom, WORLD.mouth - WORLD.back, false, L);
  bar(WORLD.w - WORLD.mouth, WORLD.goalBottom, WORLD.mouth - WORLD.back, false, R);

  // Tapas de los postes: su centro y radio coinciden con bounceCircle() del motor.
  const cap = (x: number, y: number) => {
    const color = x < WORLD.w / 2 ? L : R;
    const r = WORLD.postR;
    ctx.beginPath();
    ctx.arc(x, y, r, 0, Math.PI * 2);
    ctx.fillStyle = "#f4efe4";
    ctx.fill();
    ctx.save();
    ctx.clip();
    ctx.fillStyle = "#cfc4ad";
    ctx.beginPath();
    ctx.arc(x - r * 0.35, y + r * 0.45, r, 0, Math.PI * 2);
    ctx.fill();
    ctx.restore();
    ctx.strokeStyle = "#21151f";
    ctx.lineWidth = 2.2;
    ctx.beginPath();
    ctx.arc(x, y, r, 0, Math.PI * 2);
    ctx.stroke();
    ctx.fillStyle = color;
    ctx.beginPath();
    ctx.arc(x, y, r * 0.5, 0, Math.PI * 2);
    ctx.fill();
    ctx.lineWidth = 1.6;
    ctx.stroke();
    ctx.fillStyle = "rgba(255,255,255,0.85)";
    ctx.beginPath();
    ctx.ellipse(x + 3.5, y - 6, 4, 2.2, -0.4, 0, Math.PI * 2);
    ctx.fill();
  };
  cap(WORLD.mouth, WORLD.goalTop);
  cap(WORLD.w - WORLD.mouth, WORLD.goalTop);
  cap(WORLD.mouth, WORLD.goalBottom);
  cap(WORLD.w - WORLD.mouth, WORLD.goalBottom);
}

function drawGoalCelebration(ctx: CanvasRenderingContext2D, m: Match, time: number) {
  if (m.phase !== "goal") return;
  const left = m.ball.x < WORLD.w / 2;
  const mouthX = left ? WORLD.mouth : WORLD.w - WORLD.mouth;
  const cy = (WORLD.goalTop + WORLD.goalBottom) / 2;
  const pulse = 0.72 + Math.sin(time * 28) * 0.18;
  const radius = 150 + Math.sin(time * 17) * 20;
  const flash = ctx.createRadialGradient(mouthX, cy, 4, mouthX, cy, radius);
  flash.addColorStop(0, `rgba(255, 231, 161, ${0.42 * pulse})`);
  flash.addColorStop(0.45, left ? `rgba(255, 90, 54, ${0.2 * pulse})` : `rgba(61, 139, 253, ${0.2 * pulse})`);
  flash.addColorStop(1, "rgba(0,0,0,0)");
  ctx.fillStyle = flash;
  ctx.beginPath();
  ctx.arc(mouthX, cy, radius, 0, Math.PI * 2);
  ctx.fill();
}

function drawShadow(ctx: CanvasRenderingContext2D, x: number, rx: number) {
  ctx.fillStyle = "rgba(0,0,0,0.28)";
  ctx.beginPath();
  ctx.ellipse(x, WORLD.ground - 2, rx, 6, 0, 0, Math.PI * 2);
  ctx.fill();
}


function moodFor(
  f: Fighter,
  scoringTeam: "left" | "right" | null,
  winningTeam: "left" | "right" | null,
): FighterMood {
  if (scoringTeam) return f.team === scoringTeam ? "victory" : "defeat";
  if (winningTeam) return f.team === winningTeam ? "victory" : "defeat";
  return "play";
}

/**
 * El disco del power-up: círculo con el interior morado (la figura que
 * Rafael adjuntó). Se usa dentro de la burbuja, como ítem suelto y como
 * disco defensivo en la portería.
 */
function drawPowerDisc(ctx: CanvasRenderingContext2D, x: number, y: number, r: number) {
  ctx.save();
  ctx.translate(x, y);
  // Aro exterior crema con contorno oscuro.
  ctx.beginPath();
  ctx.arc(0, 0, r, 0, Math.PI * 2);
  ctx.fillStyle = PAPER;
  ctx.fill();
  ctx.strokeStyle = INK;
  ctx.lineWidth = 3;
  ctx.stroke();
  // Círculo interno morado, recortado al aro.
  ctx.save();
  ctx.beginPath();
  ctx.arc(0, 0, r - 1.2, 0, Math.PI * 2);
  ctx.clip();
  ctx.beginPath();
  ctx.arc(0, 0, r * 0.62, 0, Math.PI * 2);
  ctx.fillStyle = POWERUP.purple;
  ctx.fill();
  ctx.beginPath();
  ctx.arc(0, 0, r * 0.62, 0, Math.PI * 2);
  ctx.strokeStyle = POWERUP.purpleDark;
  ctx.lineWidth = 2;
  ctx.stroke();
  // Brillo superior izquierdo, como en la figura.
  ctx.beginPath();
  ctx.arc(-r * 0.22, -r * 0.26, r * 0.2, 0, Math.PI * 2);
  ctx.fillStyle = "rgba(255,255,255,0.55)";
  ctx.fill();
  ctx.restore();
  ctx.restore();
}

/** Burbuja, ítem suelto y disco defensivo del power-up. */
function drawPowerup(ctx: CanvasRenderingContext2D, m: Match, time: number) {
  if (m.bubble) {
    const by = bubbleY(m.bubble);
    const pulse = 1 + 0.05 * Math.sin(m.bubble.bobT * 3);
    const r = m.bubble.r * pulse;
    // Esfera translúcida con brillo.
    ctx.save();
    ctx.beginPath();
    ctx.arc(m.bubble.x, by, r + 6, 0, Math.PI * 2);
    ctx.fillStyle = "rgba(190, 220, 255, 0.18)";
    ctx.fill();
    ctx.beginPath();
    ctx.arc(m.bubble.x, by, r, 0, Math.PI * 2);
    ctx.fillStyle = "rgba(220, 235, 255, 0.28)";
    ctx.fill();
    ctx.strokeStyle = "rgba(255,255,255,0.85)";
    ctx.lineWidth = 2.5;
    ctx.stroke();
    ctx.beginPath();
    ctx.arc(m.bubble.x - r * 0.35, by - r * 0.4, r * 0.22, 0, Math.PI * 2);
    ctx.fillStyle = "rgba(255,255,255,0.75)";
    ctx.fill();
    ctx.restore();
    drawPowerDisc(ctx, m.bubble.x, by, r * 0.55);
  }

  if (m.item) {
    const pulse = 1 + 0.08 * Math.sin(time * 6);
    // Halo morado para que se vea que es coleccionable.
    ctx.save();
    ctx.beginPath();
    ctx.arc(m.item.x, m.item.y, m.item.r + 10, 0, Math.PI * 2);
    ctx.fillStyle = "rgba(168, 85, 247, 0.22)";
    ctx.fill();
    ctx.restore();
    drawPowerDisc(ctx, m.item.x, m.item.y, m.item.r * pulse);
  }

  for (const disc of shieldDiscs(m)) {
    // Cada disco oscila en su portería; parpadea cuando se agota.
    const blink = disc.t < 1.5 ? (Math.sin(time * 14) > 0 ? 1 : 0.45) : 1;
    ctx.save();
    ctx.globalAlpha = blink;
    ctx.beginPath();
    ctx.arc(disc.x, disc.y, disc.r + 8, 0, Math.PI * 2);
    ctx.fillStyle = "rgba(168, 85, 247, 0.20)";
    ctx.fill();
    ctx.restore();
    drawPowerDisc(ctx, disc.x, disc.y, disc.r);
  }
}

function drawBall(ctx: CanvasRenderingContext2D, b: Ball, sudden: boolean) {

  const sp = Math.hypot(b.vx, b.vy);
  const squash = Math.min(0.22, sp / 1900);
  const ang = Math.atan2(b.vy, b.vx);
  ctx.save();
  ctx.translate(b.x, b.y);
  if (b.flame > 0.05) {
    // Halo de fuego con dos círculos translúcidos. Antes era shadowBlur,
    // que obliga a la GPU a desenfocar CADA trazo de la pelota (~12) y en
    // el celular provocaba tirones justo en los tiros fuertes.
    const k = Math.min(1, b.flame);
    ctx.fillStyle = `rgba(255, 138, 0, ${0.16 + k * 0.1})`;
    ctx.beginPath();
    ctx.arc(0, 0, b.r + 11 + k * 7, 0, Math.PI * 2);
    ctx.fill();
    ctx.fillStyle = `rgba(255, 170, 40, ${0.22 + k * 0.12})`;
    ctx.beginPath();
    ctx.arc(0, 0, b.r + 5 + k * 3, 0, Math.PI * 2);
    ctx.fill();
  }
  ctx.rotate(ang);
  ctx.scale(1 + squash, 1 - squash * 0.72);
  ctx.rotate(-ang);
  ctx.rotate(b.spin);

  // Balón FUTGOGOS: contorno grueso, gajos que se leen al girar y brillo plano.
  ctx.beginPath();
  ctx.arc(0, 0, b.r, 0, Math.PI * 2);
  ctx.fillStyle = sudden || b.flame > 0.4 ? "#ffd35a" : PAPER;
  ctx.fill();
  ctx.strokeStyle = INK;
  ctx.lineWidth = 3;
  ctx.stroke();

  ctx.save();
  ctx.beginPath();
  ctx.arc(0, 0, b.r - 1.2, 0, Math.PI * 2);
  ctx.clip();

  // Central panel.
  ctx.beginPath();
  for (let i = 0; i < 5; i++) {
    const a = -Math.PI / 2 + (i * Math.PI * 2) / 5;
    const px = Math.cos(a) * b.r * 0.38;
    const py = Math.sin(a) * b.r * 0.38;
    if (i === 0) ctx.moveTo(px, py);
    else ctx.lineTo(px, py);
  }
  ctx.closePath();
  ctx.fillStyle = "#2c2231";
  ctx.fill();
  ctx.strokeStyle = "#2c2231";
  ctx.lineWidth = 2;
  ctx.stroke();

  // Visible seams between panels.
  for (let i = 0; i < 5; i++) {
    const a = -Math.PI / 2 + (i * Math.PI * 2) / 5;
    ctx.beginPath();
    ctx.moveTo(Math.cos(a) * b.r * 0.4, Math.sin(a) * b.r * 0.4);
    ctx.lineTo(Math.cos(a) * b.r * 1.15, Math.sin(a) * b.r * 1.15);
    ctx.stroke();
  }
  ctx.restore();

  // Simple collectible-toy shine.
  ctx.strokeStyle = "rgba(255,255,255,0.82)";
  ctx.lineWidth = 2.4;
  ctx.lineCap = "round";
  ctx.beginPath();
  ctx.arc(-1, -1, b.r * 0.62, Math.PI * 1.08, Math.PI * 1.46);
  ctx.stroke();
  ctx.restore();
}


// Scratch mutable reutilizado por las 8 previews del roster. Se inicializa una
// sola vez; el dibujo no reserva objetos por frame.
const PREVIEW_BALL: Ball = {
  x: 100,
  y: -18,
  vx: 0,
  vy: 0,
  r: 16,
  spin: 0,
  spinV: 0,
  flame: 0,
  bounceCd: 0,
  flameAcc: 0,
};
const PREVIEW_FIGHTER: Fighter = {
  id: 0,
  team: "left",
  control: "bot",
  name: "",
  character: "tizo",
  x: 0,
  y: 0,
  vx: 0,
  vy: 0,
  facing: 1,
  grounded: true,
  coyote: 0,
  jumpBuf: 0,
  jumpsLeft: 2,
  hover: 0,
  hovering: false,
  stun: 0,
  charge: 0,
  atk: "idle",
  atkT: 0,
  atkPower: "normal",
  hitBall: false,
  hitIds: [],
  didLunge: false,
  anim: 0,
  landSquash: 0,
  touchCd: 0,
  mind: {
    wait: 0,
    axis: 0,
    jumpPulse: 0,
    doubleJumpNow: false,
    attackPulse: 0,
    downPulse: 0,
    defend: false,
    prevJump: false,
    prevAttack: false,
    prevDown: false,
  },
};

export type PreviewAction = "idle" | "run" | "combo";

export function drawCharacterPreview(
  ctx: CanvasRenderingContext2D,
  characterId: CharacterId,
  x: number,
  y: number,
  scale: number,
  time: number,
  opts: { facing?: 1 | -1; team?: "left" | "right"; action?: PreviewAction } = {},
) {
  const f = PREVIEW_FIGHTER;
  const action = opts.action ?? "idle";
  f.character = characterId;
  f.team = opts.team ?? "left";
  f.facing = opts.facing ?? 1;
  f.name = getCharacter(characterId).name;
  f.x = 0;
  f.y = 0;
  f.anim = time;
  f.grounded = true;
  f.hovering = false;
  f.stun = 0;
  f.charge = 0;
  f.atk = "idle";
  f.atkT = 0;
  f.atkPower = "normal";
  f.landSquash = 0;
  f.vx = 0;
  f.vy = 0;
  if (action === "run") {
    f.vx = 300 * f.facing;
    f.anim = time * 1.6;
  } else if (action === "combo") {
    // Demostración en bucle: guardia, carga, golpe+patada, recuperación.
    const t = time % 1.6;
    if (t > 0.9 && t < 0.98) {
      f.atk = "startup";
      f.atkT = (t - 0.9) * 0.5;
    } else if (t >= 0.98 && t < 1.2) {
      f.atk = "active";
      f.atkT = Math.min(0.08, (t - 0.98) * 0.4);
    } else if (t >= 1.2 && t < 1.45) {
      f.atk = "recover";
      f.atkT = (t - 1.2) * 0.56;
    }
  }
  ctx.save();
  ctx.translate(x, y);
  ctx.scale(scale, scale);
  ctx.fillStyle = "rgba(0,0,0,0.24)";
  ctx.beginPath();
  ctx.ellipse(0, 34, 17, 5, 0, 0, Math.PI * 2);
  ctx.fill();
  drawFighter(ctx, f, PREVIEW_BALL, time, "play");
  ctx.restore();
}

function drawParticle(ctx: CanvasRenderingContext2D, p: Particle) {
  const a = Math.max(0, p.life / p.max);
  ctx.save();
  ctx.globalAlpha = a;
  ctx.strokeStyle = INK;
  ctx.lineWidth = 1.3;
  if (p.kind === "confetti") {
    ctx.translate(p.x, p.y);
    ctx.rotate(p.life * 8);
    ctx.fillStyle = p.color;
    roundRect(ctx, -p.size / 2, -p.size / 4, p.size, p.size / 2, 1);
    ctx.fill();
    ctx.stroke();
    ctx.fillStyle = "rgba(255,255,255,0.55)";
    ctx.fillRect(-p.size / 2 + 1, -p.size / 4 + 1, p.size * 0.3, 1.5);
  } else if (p.kind === "spark") {
    ctx.translate(p.x, p.y);
    ctx.rotate(p.life * 5);
    ctx.fillStyle = p.color;
    ctx.beginPath();
    ctx.moveTo(0, -p.size);
    ctx.lineTo(p.size * 0.34, -p.size * 0.32);
    ctx.lineTo(p.size, 0);
    ctx.lineTo(p.size * 0.34, p.size * 0.32);
    ctx.lineTo(0, p.size);
    ctx.lineTo(-p.size * 0.34, p.size * 0.32);
    ctx.lineTo(-p.size, 0);
    ctx.lineTo(-p.size * 0.34, -p.size * 0.32);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
  } else {
    ctx.fillStyle = p.kind === "flame" ? p.color : p.color;
    ctx.beginPath();
    ctx.arc(p.x, p.y, Math.max(1.2, p.size * a), 0, Math.PI * 2);
    ctx.fill();
    ctx.stroke();
    if (p.kind === "flame") {
      ctx.fillStyle = PAPER;
      ctx.beginPath();
      ctx.arc(p.x - 1, p.y - 1, Math.max(0.8, p.size * a * 0.28), 0, Math.PI * 2);
      ctx.fill();
    }
  }
  ctx.restore();
}

function drawFloat(
  ctx: CanvasRenderingContext2D,
  t: { text: string; x: number; y: number; life: number; max: number; color: string },
) {
  ctx.globalAlpha = Math.max(0, Math.min(1, t.life / t.max));
  ctx.fillStyle = t.color;
  ctx.font = '800 28px "Lilita One", "Arial Black", sans-serif';
  ctx.textAlign = "center";
  ctx.fillText(t.text, t.x, t.y);
  ctx.globalAlpha = 1;
}

function drawOffscreen(ctx: CanvasRenderingContext2D, m: Match, cam: Camera) {
  const ballX = cam.ox + (m.ball.x - cam.x) * cam.scale;
  const ballY = cam.oy + (m.ball.y - cam.y) * cam.scale;
  const pad = 16;
  if (ballX < pad || ballX > ctx.canvas.width - pad || ballY < pad || ballY > ctx.canvas.height - pad) {
    const x = Math.max(pad, Math.min(ctx.canvas.width - pad, ballX));
    const y = Math.max(pad, Math.min(ctx.canvas.height - pad, ballY));
    ctx.fillStyle = "#f6efe2";
    ctx.beginPath();
    ctx.arc(x, y, 8, 0, Math.PI * 2);
    ctx.fill();
    ctx.fillStyle = "#1b2430";
    ctx.beginPath();
    ctx.arc(x, y, 3, 0, Math.PI * 2);
    ctx.fill();
  }
}
