/**
 * Render chibi 2.5D de los Goal Fighters.
 *
 * Estilo: cabezón (≈45 % de la altura), contorno de tinta grueso, sombreado
 * "cel" de dos tonos con la luz arriba-delante, extremidades traseras más
 * oscuras para dar profundidad y una cara en 3/4 que mira hacia donde corre.
 *
 * Todo sale de dos fuentes:
 *   - `LookPalette` (fighter-style.ts): QUÉ se dibuja (patrón de estilo).
 *   - `Pose` (fighter-rig.ts): DÓNDE está cada articulación este frame.
 * No se reservan objetos de canvas por frame: sin degradados, sin sombras
 * con blur; solo trazados planos, que es lo que mejor rinde en el móvil.
 */
import { INK, PAPER, TEAM_COLOR, type BrowStyle, type Character, type EyeStyle, type MouthStyle } from "./characters.ts";
import type { Ball, Fighter } from "./engine.ts";
import { attackReach } from "./engine.ts";
import { paletteForCharacter, paletteOf, type FighterLook, type HairStyle, type LookPalette } from "./fighter-style.ts";
import { poseFor, type FaceMode, type FighterMood, type Limb, type Pose } from "./fighter-rig.ts";

export type { FighterMood } from "./fighter-rig.ts";

/** Lo que necesitan cabeza, cara y accesorios (mismos nombres que `Character`). */
type HeadParts = Pick<Character, "head" | "hair" | "accent" | "accessory" | "skin">;

const headPartsCache = new WeakMap<LookPalette, HeadParts>();

function headParts(p: LookPalette): HeadParts {
  let h = headPartsCache.get(p);
  if (!h) {
    h = { head: p.look.head, hair: p.hair, accent: p.accent, accessory: p.look.accessory, skin: p.skin };
    headPartsCache.set(p, h);
  }
  return h;
}

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();
}

const OUTLINE = 3.2;
const HEAD_BASE = 0.84;

/* ------------------------------ Extremidades ------------------------------ */

function limbPath(ctx: CanvasRenderingContext2D, l: Limb) {
  ctx.beginPath();
  ctx.moveTo(l.root.x, l.root.y);
  ctx.lineTo(l.joint.x, l.joint.y);
  ctx.lineTo(l.end.x, l.end.y);
}

/** Brazo o pierna: contorno, color base y una franja de sombra en el lado de atrás. */
function drawLimb(ctx: CanvasRenderingContext2D, l: Limb, w: number, base: string, shade: string) {
  ctx.lineCap = "round";
  ctx.lineJoin = "round";
  limbPath(ctx, l);
  ctx.strokeStyle = INK;
  ctx.lineWidth = w + OUTLINE * 1.4;
  ctx.stroke();
  ctx.strokeStyle = base;
  ctx.lineWidth = w;
  ctx.stroke();
  ctx.save();
  ctx.translate(-w * 0.2, w * 0.16);
  limbPath(ctx, l);
  ctx.strokeStyle = shade;
  ctx.lineWidth = w * 0.36;
  ctx.stroke();
  ctx.restore();
}

/** Calceta: cubre la espinilla (de un poco bajo la rodilla al tobillo). */
function drawSock(ctx: CanvasRenderingContext2D, l: Limb, w: number, color: string) {
  const sx = l.joint.x + (l.end.x - l.joint.x) * 0.28;
  const sy = l.joint.y + (l.end.y - l.joint.y) * 0.28;
  ctx.lineCap = "round";
  ctx.strokeStyle = color;
  ctx.lineWidth = w + 0.6;
  ctx.beginPath();
  ctx.moveTo(sx, sy);
  ctx.lineTo(l.end.x, l.end.y);
  ctx.stroke();
  // Doblez de la calceta.
  ctx.strokeStyle = INK;
  ctx.lineWidth = 1.3;
  const nx = -(l.end.y - l.joint.y);
  const ny = l.end.x - l.joint.x;
  const nl = Math.hypot(nx, ny) || 1;
  const k = (w * 0.55) / nl;
  ctx.beginPath();
  ctx.moveTo(sx - nx * k, sy - ny * k);
  ctx.lineTo(sx + nx * k, sy + ny * k);
  ctx.stroke();
}

/** Manga corta sobre el primer tramo del brazo. */
function drawSleeve(ctx: CanvasRenderingContext2D, l: Limb, w: number, color: string) {
  const ex = l.root.x + (l.joint.x - l.root.x) * 0.5;
  const ey = l.root.y + (l.joint.y - l.root.y) * 0.5;
  ctx.lineCap = "round";
  ctx.strokeStyle = INK;
  ctx.lineWidth = w + 2.2 + OUTLINE;
  ctx.beginPath();
  ctx.moveTo(l.root.x, l.root.y);
  ctx.lineTo(ex, ey);
  ctx.stroke();
  ctx.strokeStyle = color;
  ctx.lineWidth = w + 2.2;
  ctx.stroke();
}

function drawFist(ctx: CanvasRenderingContext2D, x: number, y: number, r: number, base: string, shade: string, light: string) {
  ctx.beginPath();
  ctx.arc(x, y, r, 0, Math.PI * 2);
  ctx.fillStyle = base;
  ctx.fill();
  ctx.save();
  ctx.clip();
  ctx.fillStyle = shade;
  ctx.beginPath();
  ctx.arc(x - r * 0.45, y + r * 0.5, r, 0, Math.PI * 2);
  ctx.fill();
  ctx.restore();
  ctx.strokeStyle = INK;
  ctx.lineWidth = 2.6;
  ctx.beginPath();
  ctx.arc(x, y, r, 0, Math.PI * 2);
  ctx.stroke();
  // Nudillos.
  ctx.lineWidth = 1.2;
  ctx.beginPath();
  ctx.moveTo(x + r * 0.15, y - r * 0.55);
  ctx.lineTo(x + r * 0.15, y + r * 0.2);
  ctx.stroke();
  ctx.fillStyle = light;
  ctx.beginPath();
  ctx.arc(x + r * 0.35, y - r * 0.4, r * 0.28, 0, Math.PI * 2);
  ctx.fill();
}

/** Botín robusto estilo arcade. El origen es la planta (y = 0 toca el suelo). */
function drawBoot(
  ctx: CanvasRenderingContext2D,
  x: number,
  y: number,
  rot: number,
  big: boolean,
  base: string,
  shade: string,
  light: string,
  sole: string,
  accent: string,
) {
  ctx.save();
  ctx.translate(x, y);
  ctx.rotate(rot);
  const s = big ? 1.18 : 1;
  ctx.scale(s, s);

  // Suela con tacos.
  roundRect(ctx, -6.5, -2.4, 16, 3.4, 1.6);
  ctx.fillStyle = sole;
  ctx.fill();
  ctx.strokeStyle = INK;
  ctx.lineWidth = 2;
  ctx.stroke();

  // Empeine: forma de gota con la punta hacia delante.
  ctx.beginPath();
  ctx.moveTo(-6.2, -2);
  ctx.quadraticCurveTo(-7.4, -10.5, 0.5, -10.2);
  ctx.quadraticCurveTo(5, -9.6, 7.5, -5.6);
  ctx.quadraticCurveTo(10.6, -3.4, 9.4, -1.8);
  ctx.closePath();
  ctx.fillStyle = base;
  ctx.fill();
  ctx.save();
  ctx.clip();
  ctx.fillStyle = shade;
  ctx.fillRect(-8, -5, 20, 4);
  ctx.restore();
  ctx.strokeStyle = INK;
  ctx.lineWidth = 2.4;
  ctx.stroke();

  // Franja lateral de acento y brillo.
  ctx.strokeStyle = accent;
  ctx.lineWidth = 1.8;
  ctx.lineCap = "round";
  ctx.beginPath();
  ctx.moveTo(-3.2, -6.4);
  ctx.lineTo(3.6, -4.2);
  ctx.stroke();
  ctx.fillStyle = light;
  ctx.globalAlpha *= 0.85;
  ctx.beginPath();
  ctx.ellipse(-1.6, -8.2, 2.6, 1.1, -0.15, 0, Math.PI * 2);
  ctx.fill();
  ctx.restore();
}

/* --------------------------------- Torso ---------------------------------- */

function torsoPath(ctx: CanvasRenderingContext2D, w: number) {
  // Torso "bean": pecho amplio, cintura algo más estrecha; base en y = 2, hombros en y = -17.
  ctx.beginPath();
  ctx.moveTo(-w + 2, 3);
  ctx.quadraticCurveTo(-w - 1.5, -8, -w + 1.5, -15);
  ctx.quadraticCurveTo(0, -20.5, w - 1, -15.5);
  ctx.quadraticCurveTo(w + 2.5, -8, w - 1, 3);
  ctx.quadraticCurveTo(0, 5.5, -w + 2, 3);
  ctx.closePath();
}

function drawKitPattern(ctx: CanvasRenderingContext2D, pattern: string, w: number, color: string) {
  ctx.fillStyle = color;
  if (pattern === "stripes") {
    for (let x = -w + 1; x < w; x += 7) ctx.fillRect(x, -22, 3.2, 28);
  } else if (pattern === "hoops") {
    for (let y = -15; y < 4; y += 7) ctx.fillRect(-w - 2, y, w * 2 + 4, 3.4);
  } else if (pattern === "sash") {
    ctx.beginPath();
    ctx.moveTo(-w - 2, -16);
    ctx.lineTo(-w + 6, -20);
    ctx.lineTo(w + 3, 2);
    ctx.lineTo(w - 5, 6);
    ctx.closePath();
    ctx.fill();
  } else if (pattern === "split") {
    ctx.fillRect(1, -22, w + 4, 30);
  } else if (pattern === "chevron") {
    ctx.beginPath();
    ctx.moveTo(-w - 2, -12);
    ctx.lineTo(0, -4);
    ctx.lineTo(w + 2, -12);
    ctx.lineTo(w + 2, -7);
    ctx.lineTo(0, 1);
    ctx.lineTo(-w - 2, -7);
    ctx.closePath();
    ctx.fill();
  }
}

const NUMBER_FONT = "15px 'Lilita One', 'Arial Black', sans-serif";

function drawTorso(ctx: CanvasRenderingContext2D, pal: LookPalette, team: "left" | "right", facing: 1 | -1) {
  const w = pal.spec.torsoW;
  torsoPath(ctx, w);
  ctx.fillStyle = pal.shirt;
  ctx.fill();
  ctx.save();
  ctx.clip();
  drawKitPattern(ctx, pal.look.kit.pattern, w, pal.pattern);
  // Sombra cel en la espalda y bajo el pecho (la luz viene de arriba-delante).
  ctx.fillStyle = pal.shirtShade;
  ctx.globalAlpha = 0.85;
  ctx.beginPath();
  ctx.ellipse(-w - 2, -4, w * 0.75, 15, 0.1, 0, Math.PI * 2);
  ctx.fill();
  ctx.globalAlpha = 0.45;
  ctx.fillRect(-w - 2, -1, w * 2 + 4, 6);
  ctx.globalAlpha = 1;
  // Brillo de volumen en el pecho.
  ctx.fillStyle = pal.shirtLight;
  ctx.globalAlpha = 0.55;
  ctx.beginPath();
  ctx.ellipse(w * 0.35, -12, w * 0.42, 3.4, -0.25, 0, Math.PI * 2);
  ctx.fill();
  ctx.globalAlpha = 1;
  ctx.restore();

  // Cuello en V con el color del equipo: identifica izquierda/derecha.
  ctx.fillStyle = TEAM_COLOR[team];
  ctx.beginPath();
  ctx.moveTo(-5.5, -17.2);
  ctx.lineTo(1.5, -10.5);
  ctx.lineTo(7.5, -17.5);
  ctx.lineTo(4.5, -18.5);
  ctx.lineTo(1.5, -14.5);
  ctx.lineTo(-2.5, -18.3);
  ctx.closePath();
  ctx.fill();

  torsoPath(ctx, w);
  ctx.strokeStyle = INK;
  ctx.lineWidth = OUTLINE;
  ctx.stroke();

  // Dorsal en el pecho (sin espejar el número al mirar a la izquierda).
  const num = pal.look.kit.number;
  if (num > 0) {
    ctx.save();
    ctx.translate(w * 0.32, -5);
    ctx.scale(facing, 1);
    ctx.font = NUMBER_FONT;
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.lineWidth = 3;
    ctx.strokeStyle = INK;
    ctx.strokeText(String(num), 0, 0);
    ctx.fillStyle = PAPER;
    ctx.fillText(String(num), 0, 0);
    ctx.restore();
  }
}

function drawShorts(ctx: CanvasRenderingContext2D, pal: LookPalette) {
  const w = pal.spec.torsoW;
  ctx.beginPath();
  ctx.moveTo(-w + 1, -2);
  ctx.lineTo(w - 0.5, -2);
  ctx.lineTo(w + 0.5, 7);
  ctx.quadraticCurveTo(w * 0.5, 9.5, 1, 6);
  ctx.quadraticCurveTo(-w * 0.5, 9.5, -w - 0.5, 7);
  ctx.closePath();
  ctx.fillStyle = pal.shorts;
  ctx.fill();
  ctx.save();
  ctx.clip();
  ctx.fillStyle = pal.shortsShade;
  ctx.fillRect(-w - 2, 3, w * 2 + 4, 8);
  ctx.restore();
  ctx.strokeStyle = INK;
  ctx.lineWidth = OUTLINE * 0.85;
  ctx.stroke();
}

/* ---------------------------------- Pelo ---------------------------------- */

function drawHairBack(ctx: CanvasRenderingContext2D, style: HairStyle, pal: LookPalette, hw: number, hh: number, cy: number) {
  if (style !== "bob" && style !== "curly") return;
  ctx.fillStyle = pal.hairShade;
  ctx.strokeStyle = INK;
  ctx.lineWidth = 2.6;
  ctx.beginPath();
  if (style === "bob") {
    ctx.ellipse(-3, cy + 2, hw + 3, hh + 1, 0, 0, Math.PI * 2);
  } else {
    for (let i = 0; i < 7; i++) {
      const a = Math.PI * (0.55 + i * 0.16);
      const x = -2 + Math.cos(a) * (hw + 2);
      const y = cy - 2 + Math.sin(a) * (hh + 1);
      ctx.moveTo(x + 6, y);
      ctx.arc(x, y, 6, 0, Math.PI * 2);
    }
  }
  ctx.fill();
  ctx.stroke();
}

function drawHairFront(ctx: CanvasRenderingContext2D, style: HairStyle, pal: LookPalette, hw: number, hh: number, cy: number) {
  if (style === "none") return;
  const top = cy - hh;
  ctx.fillStyle = pal.hair;
  ctx.strokeStyle = INK;
  ctx.lineWidth = 2.6;
  ctx.lineJoin = "round";
  ctx.beginPath();
  if (style === "short" || style === "bob" || style === "curly") {
    // Casquete sobre la parte alta y la nuca.
    ctx.moveTo(-hw - 0.5, cy - 1);
    ctx.quadraticCurveTo(-hw - 2, top - 3, 2, top - 2.5);
    ctx.quadraticCurveTo(hw + 2, top - 1, hw + 0.5, cy - hh * 0.45);
    ctx.quadraticCurveTo(hw * 0.4, cy - hh * 0.62, 2, cy - hh * 0.5);
    ctx.quadraticCurveTo(-hw * 0.5, cy - hh * 0.6, -hw * 0.55, cy + 1);
    ctx.closePath();
  } else if (style === "spiky") {
    ctx.moveTo(-hw - 1, cy - 2);
    const n = 5;
    for (let i = 0; i <= n; i++) {
      const t = i / n;
      const x = -hw + t * hw * 2.1;
      const y = top + Math.sin(t * Math.PI) * -1 - 1;
      ctx.lineTo(x - 4, y + 3);
      ctx.lineTo(x + 1 + t * 3, y - 9 + Math.abs(t - 0.6) * 6);
    }
    ctx.lineTo(hw + 1, cy - hh * 0.4);
    ctx.quadraticCurveTo(0, cy - hh * 0.62, -hw * 0.55, cy);
    ctx.closePath();
  } else if (style === "swoop") {
    ctx.moveTo(-hw - 1, cy);
    ctx.quadraticCurveTo(-hw - 2, top - 4, 3, top - 3);
    ctx.quadraticCurveTo(hw + 9, top - 1, hw + 6, cy - hh * 0.2);
    ctx.quadraticCurveTo(hw * 0.3, cy - hh * 0.75, -hw * 0.5, cy + 1);
    ctx.closePath();
  }
  ctx.fill();
  ctx.stroke();
  // Brillo del pelo.
  ctx.strokeStyle = pal.hairLight;
  ctx.lineWidth = 2;
  ctx.lineCap = "round";
  ctx.beginPath();
  ctx.arc(1, cy - 1, hh * 0.86, Math.PI * 1.35, Math.PI * 1.6);
  ctx.stroke();
}

/* --------------------------------- Cabeza --------------------------------- */

/** Accesorios que ya forman el pelo o lo tapan (no se dibuja peinado debajo). */
function hairFor(pal: LookPalette): HairStyle {
  const acc = pal.look.accessory;
  if (acc === "mohawk" || acc === "helmet" || acc === "beanie") return "none";
  return pal.look.hair.style;
}

function drawHead(ctx: CanvasRenderingContext2D, pal: LookPalette, pose: Pose, lookX: number) {
  const parts = headParts(pal);
  const hw = headWidth(parts);
  const hh = headHeight(parts);
  const hair = hairFor(pal);
  const mode = pose.face;
  // El código de cara/accesorios trabaja con la cabeza centrada en (0, -15).
  const cy = -15;

  ctx.save();
  ctx.translate(pose.head.x, pose.head.y - cy);
  ctx.translate(0, cy);
  ctx.rotate(pose.headTilt);
  // 0.84: cabeza grande (≈50 % de la altura) pero sin tapar torso ni brazos.
  const hs = HEAD_BASE * pal.look.headScale;
  ctx.scale(hs, hs);
  ctx.translate(0, -cy);

  drawAccessoryBack(ctx, parts, cy);
  drawHairBack(ctx, hair, pal, hw, hh, cy);

  headPath(ctx, parts, 0, cy);
  ctx.fillStyle = pal.skin;
  ctx.fill();
  ctx.save();
  ctx.clip();
  // Sombra cel: media luna en la nuca y bajo la barbilla.
  ctx.fillStyle = pal.skinShade;
  ctx.beginPath();
  ctx.ellipse(-hw * 0.95, cy + hh * 0.35, hw * 0.75, hh * 1.05, 0, 0, Math.PI * 2);
  ctx.fill();
  ctx.globalAlpha = 0.5;
  ctx.beginPath();
  ctx.ellipse(2, cy + hh * 1.08, hw * 1.1, hh * 0.32, 0, 0, Math.PI * 2);
  ctx.fill();
  ctx.globalAlpha = 1;
  // Brillo de volumen en la frente.
  ctx.fillStyle = pal.skinLight;
  ctx.globalAlpha = 0.7;
  ctx.beginPath();
  ctx.ellipse(hw * 0.28, cy - hh * 0.52, hw * 0.42, hh * 0.2, -0.2, 0, Math.PI * 2);
  ctx.fill();
  ctx.globalAlpha = 1;
  ctx.restore();
  headPath(ctx, parts, 0, cy);
  ctx.strokeStyle = INK;
  ctx.lineWidth = OUTLINE + 0.4;
  ctx.stroke();

  drawHairFront(ctx, hair, pal, hw, hh, cy);

  // Cara en 3/4: los rasgos se corren hacia el lado al que mira.
  ctx.save();
  ctx.translate(3, 0);
  if (pal.look.face.blush && mode !== "stun") {
    ctx.fillStyle = pal.blush;
    ctx.beginPath();
    ctx.ellipse(-12, cy + 7, 4, 2.4, 0, 0, Math.PI * 2);
    ctx.ellipse(13, cy + 7, 4, 2.4, 0, 0, Math.PI * 2);
    ctx.fill();
  }
  drawMouth(ctx, 0, -3, pal.look.face.mouth, mode);
  drawEye(ctx, -9, -17, pal.look.face.eyes, lookX, mode, -1);
  drawEye(ctx, 9, -17, pal.look.face.eyes, lookX, mode, 1);
  const browMode = mode === "sad" ? "sad" : mode === "effort" || mode === "stun" ? "effort" : "normal";
  drawBrow(ctx, -9, -27, pal.look.face.brows, browMode, -1);
  drawBrow(ctx, 9, -27, pal.look.face.brows, browMode, 1);
  ctx.restore();

  drawAccessoryFront(ctx, parts, cy);
  ctx.restore();
}

/* ------------------------------- Efectos ---------------------------------- */

function drawKickSmear(ctx: CanvasRenderingContext2D, pose: Pose, color: string) {
  const l = pose.legF;
  const dx = l.end.x - l.root.x;
  const dy = l.end.y - l.root.y;
  const r = Math.hypot(dx, dy) + 6;
  const a1 = Math.atan2(dy, dx);
  const a0 = a1 + 1.5 * pose.impact;
  ctx.fillStyle = color;
  ctx.globalAlpha = 0.5;
  ctx.beginPath();
  ctx.arc(l.root.x, l.root.y, r, a1, a0);
  ctx.arc(l.root.x, l.root.y, r - 10, a0, a1, true);
  ctx.closePath();
  ctx.fill();
  ctx.globalAlpha = 1;
}

function drawSpeedLines(ctx: CanvasRenderingContext2D, time: number, color: string) {
  ctx.strokeStyle = color;
  ctx.lineCap = "round";
  ctx.lineWidth = 2.2;
  ctx.globalAlpha = 0.65;
  ctx.beginPath();
  for (let i = 0; i < 4; i++) {
    const y = -18 + i * 11;
    const off = ((time * 260 + i * 37) % 22) - 4;
    ctx.moveTo(-26 - off, y);
    ctx.lineTo(-40 - off - (i % 2) * 8, y + 2);
  }
  ctx.stroke();
  ctx.globalAlpha = 1;
}

function drawImpactStar(ctx: CanvasRenderingContext2D, x: number, y: number, r: number, color: string) {
  ctx.fillStyle = color;
  ctx.strokeStyle = INK;
  ctx.lineWidth = 1.6;
  ctx.beginPath();
  for (let i = 0; i < 10; i++) {
    const a = (i * Math.PI) / 5;
    const rr = i % 2 === 0 ? r : r * 0.45;
    if (i === 0) ctx.moveTo(x + Math.cos(a) * rr, y + Math.sin(a) * rr);
    else ctx.lineTo(x + Math.cos(a) * rr, y + Math.sin(a) * rr);
  }
  ctx.closePath();
  ctx.fill();
  ctx.stroke();
}

/* ------------------------------- Luchador --------------------------------- */

/**
 * Dibuja un luchador con un patrón de estilo concreto. `drawFighter` lo usa
 * con la paleta de su figura del roster; un editor puede pasar cualquier look.
 */
export function drawFighterWithPalette(
  ctx: CanvasRenderingContext2D,
  f: Fighter,
  pal: LookPalette,
  ball: Ball,
  time: number,
  mood: FighterMood,
) {
  const pose = poseFor(f, time, mood, attackReach(f), pal.spec.shoulder);
  const limb = pal.spec.limb;
  const stunned = f.stun > 0;
  const blink = stunned && Math.sin(time * 34) > 0 ? 0.62 : 1;

  ctx.save();
  ctx.translate(f.x, f.y);
  ctx.scale(f.facing, 1);
  // Aplastamiento al aterrizar / estiramiento en el salto, anclado a los pies.
  const sx = 1 - pose.squash * 0.42 + pose.stretch * 0.18;
  const sy = 1 - pose.squash + pose.stretch * 0.48;
  if (sx !== 1 || sy !== 1) {
    ctx.translate(0, 34);
    ctx.scale(sx, sy);
    ctx.translate(0, -34);
  }

  // Aro de equipo en el suelo.
  if (f.grounded && mood === "play") {
    ctx.globalAlpha = 0.55;
    ctx.strokeStyle = TEAM_COLOR[f.team];
    ctx.lineWidth = 2.6;
    ctx.beginPath();
    ctx.ellipse(1, 34, 18, 5, 0, 0, Math.PI * 2);
    ctx.stroke();
  }
  ctx.globalAlpha = blink;

  if (pose.rot !== 0) {
    ctx.translate(pose.pivot.x, pose.pivot.y);
    ctx.rotate(pose.rot);
    ctx.translate(-pose.pivot.x, -pose.pivot.y);
  }

  if (f.charge > 0.05 && f.atk === "idle") {
    const pulse = 0.35 + Math.sin(time * 20) * 0.12 + f.charge * 0.24;
    ctx.strokeStyle = pal.accent;
    ctx.globalAlpha = pulse * blink;
    ctx.lineWidth = 3.5;
    ctx.beginPath();
    ctx.arc(0, 4, 22 + f.charge * 17, Math.PI * 0.72, Math.PI * 1.42);
    ctx.stroke();
    ctx.beginPath();
    ctx.arc(0, 4, 17 + f.charge * 13, Math.PI * 1.65, Math.PI * 2.28);
    ctx.stroke();
    ctx.globalAlpha = blink;
  }

  if (pose.smear === "flykick") drawSpeedLines(ctx, time, pal.accent);
  if (pose.smear === "kick" || pose.smear === "flykick") {
    drawKickSmear(ctx, pose, f.atkPower === "charged" ? pal.accent : PAPER);
  }

  // --- Capa trasera (más oscura: está más lejos de la cámara) ---
  if (!pose.backArmFront) drawBackArm(ctx, pose, pal, limb);
  drawLimb(ctx, pose.legB, limb + 1.6, pal.skinBack, pal.skinShade);
  drawSock(ctx, pose.legB, limb + 1.6, pal.socksBack);
  drawBoot(ctx, pose.legB.end.x, pose.legB.end.y + 4, pose.footRotB, false, pal.bootBack, pal.bootShade, pal.boot, pal.sole, pal.socksBack);

  // --- Pierna delantera ---
  drawLimb(ctx, pose.legF, limb + 1.6, pal.skin, pal.skinShade);
  drawSock(ctx, pose.legF, limb + 1.6, pal.socks);
  drawBoot(ctx, pose.legF.end.x, pose.legF.end.y + 4, pose.footRotF, pose.bigFoot, pal.boot, pal.bootShade, pal.bootLight, pal.sole, pal.accent);

  // --- Cuerpo ---
  ctx.save();
  ctx.translate(pose.pelvis.x, pose.pelvis.y);
  drawShorts(ctx, pal);
  ctx.rotate(pose.lean);
  drawTorso(ctx, pal, f.team, f.facing);
  ctx.restore();
  // Al correr, cuando el brazo trasero sube hacia delante, cruza por delante
  // del pecho (movimiento cruzado del atleta) en vez de esconderse detrás.
  if (pose.backArmFront) drawBackArm(ctx, pose, pal, limb);

  if (pose.smear === "stomp") {
    ctx.strokeStyle = pal.accent;
    ctx.lineWidth = 2.5;
    ctx.lineCap = "round";
    for (let i = 0; i < 3; i++) {
      const yy = -30 - i * 8 + Math.sin(time * 18 + i) * 2;
      ctx.beginPath();
      ctx.moveTo(-16 + i * 6, yy);
      ctx.lineTo(-12 + i * 6, yy + 9);
      ctx.stroke();
    }
  }

  // --- Cabeza y brazo delantero ---
  // El brazo va por delante de todo (como en los arcade), salvo cuando la
  // mano sube por encima del cuello: entonces pasa por detrás de la cabeza
  // para no taparle la cara (celebración, aleteo).
  const lookX = Math.max(-2.6, Math.min(2.6, ((ball.x - f.x) * f.facing) / 85));
  const armBehindHead = pose.armF.end.y < pose.neck.y - 4 && pose.impact === 0;
  if (armBehindHead) drawFrontArm(ctx, pose, pal, limb);
  drawHead(ctx, pal, pose, lookX);
  if (!armBehindHead) drawFrontArm(ctx, pose, pal, limb);
  if (pose.impact > 0.75 && pose.smear === "kick") {
    drawImpactStar(ctx, pose.armF.end.x + 6, pose.armF.end.y - 2, 7 + (f.atkPower === "charged" ? 3 : 0), pal.accent);
  }

  if (f.hovering) {
    for (let i = 0; i < 3; i++) {
      const yy = 31 + i * 4 + Math.sin(time * 16 + i) * 1.5;
      ctx.strokeStyle = i % 2 === 0 ? pal.accent : TEAM_COLOR[f.team];
      ctx.lineWidth = 2.4;
      ctx.beginPath();
      ctx.moveTo(-14, yy);
      ctx.lineTo(-8, yy + 2);
      ctx.moveTo(9, yy + 2);
      ctx.lineTo(15, yy);
      ctx.stroke();
    }
  }

  ctx.restore();
  ctx.globalAlpha = 1;

  if (stunned) {
    ctx.save();
    ctx.translate(f.x, f.y - 52);
    ctx.fillStyle = pal.accent;
    ctx.strokeStyle = INK;
    ctx.lineWidth = 1.5;
    for (let i = 0; i < 3; i++) {
      const a = time * 6 + (i * Math.PI * 2) / 3;
      ctx.beginPath();
      ctx.arc(Math.cos(a) * 17, Math.sin(a) * 8, 3.2, 0, Math.PI * 2);
      ctx.fill();
      ctx.stroke();
    }
    ctx.restore();
  }

  if (mood === "victory") {
    ctx.save();
    ctx.translate(f.x, f.y - 56);
    ctx.fillStyle = pal.accent;
    ctx.strokeStyle = INK;
    ctx.lineWidth = 1.4;
    for (let i = 0; i < 4; i++) {
      const a = time * 2.2 + (i * Math.PI * 2) / 4;
      const r = 20 + Math.sin(time * 4 + i) * 3;
      ctx.beginPath();
      ctx.arc(Math.cos(a) * r, Math.sin(a) * 7, 2.5, 0, Math.PI * 2);
      ctx.fill();
      ctx.stroke();
    }
    ctx.restore();
  }
}

function drawBackArm(ctx: CanvasRenderingContext2D, pose: Pose, pal: LookPalette, limb: number) {
  drawSleeve(ctx, pose.armB, limb, pal.shirtBack);
  drawLimb(ctx, pose.armB, limb, pal.skinBack, pal.skinShade);
  drawFist(ctx, pose.armB.end.x, pose.armB.end.y, pose.fistB, pal.skinBack, pal.skinShade, pal.skin);
}

function drawFrontArm(ctx: CanvasRenderingContext2D, pose: Pose, pal: LookPalette, limb: number) {
  drawSleeve(ctx, pose.armF, limb, pal.shirt);
  drawLimb(ctx, pose.armF, limb, pal.skin, pal.skinShade);
  drawFist(ctx, pose.armF.end.x, pose.armF.end.y, pose.fistF, pal.skin, pal.skinShade, pal.skinLight);
}

/** Luchador del roster. */
export function drawFighter(ctx: CanvasRenderingContext2D, f: Fighter, ball: Ball, time: number, mood: FighterMood) {
  drawFighterWithPalette(ctx, f, paletteForCharacter(f.character), ball, time, mood);
}

const lookPaletteCache = new WeakMap<FighterLook, LookPalette>();

/** Paleta de un look arbitrario (editor). Cachea por objeto: crea un look nuevo al editar. */
export function paletteForLook(look: FighterLook): LookPalette {
  let p = lookPaletteCache.get(look);
  if (!p) {
    p = paletteOf(look);
    lookPaletteCache.set(look, p);
  }
  return p;
}

/* ------------------- Cabeza, cara y accesorios (comunes) ------------------- */

function headWidth(ch: HeadParts): number {
  if (ch.head === "wide") return 27;
  if (ch.head === "bean" || ch.head === "pear") return 22;
  if (ch.head === "square" || ch.head === "diamond" || ch.head === "dome") return 23;
  if (ch.head === "oval") return 20;
  return 22;
}

function headHeight(ch: HeadParts): number {
  if (ch.head === "wide") return 20;
  if (ch.head === "bean") return 25;
  if (ch.head === "pear") return 26;
  if (ch.head === "square") return 21;
  if (ch.head === "oval") return 26;
  if (ch.head === "dome") return 22;
  if (ch.head === "diamond") return 24;
  return 23;
}

function headPath(ctx: CanvasRenderingContext2D, ch: HeadParts, cx: number, cy: number) {
  const hw = headWidth(ch);
  const hh = headHeight(ch);
  ctx.beginPath();
  if (ch.head === "round" || ch.head === "oval" || ch.head === "wide" || ch.head === "bean") {
    ctx.ellipse(cx, cy, hw, hh, 0, 0, Math.PI * 2);
  } else if (ch.head === "pear") {
    ctx.moveTo(cx - 13, cy - hh + 4);
    ctx.quadraticCurveTo(cx - hw, cy - 2, cx - hw + 2, cy + hh - 2);
    ctx.quadraticCurveTo(cx, cy + hh + 4, cx + hw - 2, cy + hh - 2);
    ctx.quadraticCurveTo(cx + hw, cy - 2, cx + 13, cy - hh + 4);
    ctx.quadraticCurveTo(cx, cy - hh - 5, cx - 13, cy - hh + 4);
  } else if (ch.head === "square") {
    roundRect(ctx, cx - hw, cy - hh, hw * 2, hh * 2, 10);
  } else if (ch.head === "dome") {
    ctx.moveTo(cx - hw, cy + hh - 2);
    ctx.quadraticCurveTo(cx - hw, cy - hh - 2, cx, cy - hh - 3);
    ctx.quadraticCurveTo(cx + hw, cy - hh - 2, cx + hw, cy + hh - 2);
    ctx.quadraticCurveTo(cx, cy + hh + 5, cx - hw, cy + hh - 2);
  } else if (ch.head === "diamond") {
    ctx.moveTo(cx, cy - hh - 2);
    ctx.lineTo(cx + hw + 1, cy - 3);
    ctx.lineTo(cx + 8, cy + hh);
    ctx.quadraticCurveTo(cx, cy + hh + 5, cx - 8, cy + hh);
    ctx.lineTo(cx - hw - 1, cy - 3);
    ctx.closePath();
  }
}

export function drawEye(
  ctx: CanvasRenderingContext2D,
  x: number,
  y: number,
  style: EyeStyle,
  lookX: number,
  mode: FaceMode,
  side: number,
) {
  if (mode === "stun" || mode === "sad") {
    ctx.strokeStyle = INK;
    ctx.lineWidth = 2.2;
    ctx.lineCap = "round";
    if (mode === "sad") {
      ctx.beginPath();
      ctx.moveTo(x - 4, y + 2);
      ctx.quadraticCurveTo(x, y - 2, x + 4, y + 2);
      ctx.stroke();
    } else {
      ctx.beginPath();
      ctx.moveTo(x - 4, y - 4);
      ctx.lineTo(x + 4, y + 4);
      ctx.moveTo(x + 4, y - 4);
      ctx.lineTo(x - 4, y + 4);
      ctx.stroke();
    }
    return;
  }
  if (mode === "happy" || style === "happy") {
    ctx.strokeStyle = INK;
    ctx.lineWidth = 2.4;
    ctx.lineCap = "round";
    ctx.beginPath();
    ctx.moveTo(x - 4.5, y + 2);
    ctx.quadraticCurveTo(x, y - 4, x + 4.5, y + 2);
    ctx.stroke();
    return;
  }
  if (style === "sleepy" && side < 0) {
    ctx.strokeStyle = INK;
    ctx.lineWidth = 2.2;
    ctx.beginPath();
    ctx.moveTo(x - 5, y);
    ctx.quadraticCurveTo(x, y + 2, x + 5, y);
    ctx.stroke();
    return;
  }
  if (style === "wink" && side < 0) {
    ctx.strokeStyle = INK;
    ctx.lineWidth = 2.2;
    ctx.beginPath();
    ctx.moveTo(x - 4, y + 1);
    ctx.quadraticCurveTo(x, y - 3, x + 4, y + 1);
    ctx.stroke();
    return;
  }
  if (style === "dot") {
    ctx.fillStyle = INK;
    ctx.beginPath();
    ctx.arc(x + lookX * 0.35, y, 2.5, 0, Math.PI * 2);
    ctx.fill();
    return;
  }
  ctx.fillStyle = PAPER;
  ctx.strokeStyle = INK;
  ctx.lineWidth = 1.8;
  if (style === "sharp" || mode === "effort") {
    ctx.beginPath();
    ctx.ellipse(x, y, 5.2, 6.6, 0.12, 0, Math.PI * 2);
    ctx.fill();
    ctx.stroke();
  } else {
    ctx.beginPath();
    ctx.ellipse(x, y, style === "wide" ? 6.3 : 5.4, style === "wide" ? 7 : 6.2, 0, 0, Math.PI * 2);
    ctx.fill();
    ctx.stroke();
  }
  ctx.fillStyle = INK;
  ctx.beginPath();
  ctx.arc(x + lookX, y + 0.6, style === "wide" ? 3.2 : 2.8, 0, Math.PI * 2);
  ctx.fill();
  ctx.fillStyle = "#ffffff";
  ctx.beginPath();
  ctx.arc(x + lookX - 1, y - 1.1, 1, 0, Math.PI * 2);
  ctx.fill();
}

function drawBrow(
  ctx: CanvasRenderingContext2D,
  x: number,
  y: number,
  style: BrowStyle,
  mode: FaceMode,
  side: number,
) {
  ctx.strokeStyle = INK;
  ctx.lineCap = "round";
  ctx.lineWidth = style === "thick" ? 3.5 : 2.3;
  ctx.beginPath();
  if (mode === "effort" || style === "angry") {
    ctx.moveTo(x - 5, y - 1);
    ctx.lineTo(x + 4, y + side * 2);
  } else if (mode === "sad" || style === "worried") {
    ctx.moveTo(x - 4, y + 2);
    ctx.quadraticCurveTo(x, y - 2, x + 4, y + 1);
  } else if (style === "arched") {
    ctx.moveTo(x - 4, y + 1);
    ctx.quadraticCurveTo(x, y - 4, x + 5, y);
  } else if (style === "thin") {
    ctx.moveTo(x - 4, y);
    ctx.lineTo(x + 4, y - 1);
  } else {
    ctx.moveTo(x - 4, y);
    ctx.lineTo(x + 4, y);
  }
  ctx.stroke();
}

function drawMouth(
  ctx: CanvasRenderingContext2D,
  x: number,
  y: number,
  style: MouthStyle,
  mode: FaceMode,
) {
  ctx.strokeStyle = INK;
  ctx.fillStyle = INK;
  ctx.lineWidth = 2.2;
  ctx.lineCap = "round";
  if (mode === "stun") {
    ctx.beginPath();
    ctx.moveTo(x - 6, y);
    ctx.quadraticCurveTo(x - 2, y - 4, x + 1, y);
    ctx.quadraticCurveTo(x + 4, y + 4, x + 7, y);
    ctx.stroke();
    return;
  }
  if (mode === "sad") {
    ctx.beginPath();
    ctx.moveTo(x - 5, y + 3);
    ctx.quadraticCurveTo(x, y - 2, x + 5, y + 3);
    ctx.stroke();
    return;
  }
  if (mode === "happy" || style === "grin" || style === "tongue" || style === "grit") {
    ctx.beginPath();
    ctx.moveTo(x - 8, y - 2);
    ctx.quadraticCurveTo(x, y + 9, x + 8, y - 2);
    ctx.quadraticCurveTo(x, y + 1, x - 8, y - 2);
    ctx.fill();
    if (style === "grit" || mode === "effort") {
      // Dientes encajados dentro de la boca: se recortan a la forma de la
      // boca para que no se salgan ni solapen el borde (como el emoji).
      // Banda pequeña (8x2): Rafael los pidió más pequeños.
      ctx.save();
      ctx.beginPath();
      ctx.moveTo(x - 8, y - 2);
      ctx.quadraticCurveTo(x, y + 9, x + 8, y - 2);
      ctx.quadraticCurveTo(x, y + 1, x - 8, y - 2);
      ctx.clip();
      ctx.fillStyle = PAPER;
      ctx.fillRect(x - 4, y, 8, 2);
      ctx.restore();
    } else if (style === "tongue") {
      ctx.fillStyle = "#f06178";
      ctx.beginPath();
      ctx.ellipse(x + 1, y + 5, 3.2, 2.2, 0, 0, Math.PI * 2);
      ctx.fill();
    }
    return;
  }
  if (style === "open") {
    ctx.beginPath();
    ctx.ellipse(x, y + 2, 4.3, 6, 0, 0, Math.PI * 2);
    ctx.fill();
    return;
  }
  if (style === "smirk") {
    ctx.beginPath();
    ctx.moveTo(x - 5, y + 1);
    ctx.quadraticCurveTo(x + 2, y + 5, x + 7, y - 1);
    ctx.stroke();
    return;
  }
  if (style === "o") {
    ctx.beginPath();
    ctx.ellipse(x, y + 1, 3, 4, 0, 0, Math.PI * 2);
    ctx.fill();
    return;
  }
  if (style === "wide") {
    // Sonrisa lineal amplia: arco bien ancho y abierto, claramente más grande que "smile".
    ctx.beginPath();
    ctx.moveTo(x - 8, y - 1);
    ctx.quadraticCurveTo(x, y + 8, x + 8, y - 1);
    ctx.stroke();
    return;
  }
  if (style === "subtle") {
    // Sonrisa lineal sutil: curva corta y plana, apenas una insinuación.
    ctx.beginPath();
    ctx.moveTo(x - 4, y);
    ctx.quadraticCurveTo(x, y + 2, x + 4, y);
    ctx.stroke();
    return;
  }
  ctx.beginPath();
  ctx.moveTo(x - 5, y);
  ctx.quadraticCurveTo(x, y + 4, x + 5, y);
  ctx.stroke();
}

function drawAccessoryBack(ctx: CanvasRenderingContext2D, ch: HeadParts, cy: number) {
  ctx.fillStyle = ch.hair;
  ctx.strokeStyle = INK;
  ctx.lineWidth = 2.6;
  if (ch.accessory === "mohawk") {
    for (let i = -1; i <= 1; i++) {
      ctx.beginPath();
      ctx.moveTo(i * 7 - 5, cy - headHeight(ch) + 3);
      ctx.lineTo(i * 8, cy - headHeight(ch) - 12 + Math.abs(i) * 3);
      ctx.lineTo(i * 7 + 5, cy - headHeight(ch) + 3);
      ctx.closePath();
      ctx.fill();
      ctx.stroke();
    }
  } else if (ch.accessory === "topknot") {
    ctx.beginPath();
    ctx.arc(0, cy - headHeight(ch) - 1, 9, 0, Math.PI * 2);
    ctx.fill();
    ctx.stroke();
    ctx.fillStyle = ch.accent;
    ctx.fillRect(-8, cy - headHeight(ch) + 3, 16, 4);
  } else if (ch.accessory === "catears") {
    ctx.beginPath();
    ctx.moveTo(-18, cy - headHeight(ch) + 3);
    ctx.lineTo(-10, cy - headHeight(ch) - 14);
    ctx.lineTo(-1, cy - headHeight(ch) + 1);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(18, cy - headHeight(ch) + 3);
    ctx.lineTo(10, cy - headHeight(ch) - 14);
    ctx.lineTo(1, cy - headHeight(ch) + 1);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
  } else if (ch.accessory === "headband") {
    ctx.strokeStyle = ch.accent;
    ctx.lineWidth = 5;
    ctx.beginPath();
    ctx.moveTo(-20, cy - 4);
    ctx.quadraticCurveTo(-30, cy - 1, -31, cy + 9);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(20, cy - 4);
    ctx.quadraticCurveTo(30, cy - 1, 31, cy + 9);
    ctx.stroke();
  } else if (ch.accessory === "glasses") {
    // Rizo-antena: mantiene una silueta propia incluso sin ver la cara.
    ctx.strokeStyle = ch.hair;
    ctx.lineWidth = 4;
    ctx.beginPath();
    ctx.moveTo(1, cy - headHeight(ch) + 2);
    ctx.quadraticCurveTo(10, cy - headHeight(ch) - 15, 2, cy - headHeight(ch) - 18);
    ctx.stroke();
    ctx.fillStyle = ch.accent;
    ctx.beginPath();
    ctx.arc(1, cy - headHeight(ch) - 20, 4.5, 0, Math.PI * 2);
    ctx.fill();
    ctx.stroke();
  }
}

function drawAccessoryFront(ctx: CanvasRenderingContext2D, ch: HeadParts, cy: number) {
  ctx.strokeStyle = INK;
  ctx.lineWidth = 2.4;
  if (ch.accessory === "beanie") {
    ctx.fillStyle = ch.hair;
    ctx.beginPath();
    ctx.arc(0, cy - 8, headWidth(ch) + 1, Math.PI, Math.PI * 2);
    ctx.lineTo(headWidth(ch), cy - 6);
    ctx.lineTo(-headWidth(ch), cy - 6);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
    ctx.fillStyle = ch.accent;
    ctx.fillRect(-headWidth(ch), cy - 8, headWidth(ch) * 2, 5);
    ctx.beginPath();
    ctx.arc(0, cy - headHeight(ch) - 5, 5.5, 0, Math.PI * 2);
    ctx.fill();
    ctx.stroke();
  } else if (ch.accessory === "helmet") {
    ctx.fillStyle = ch.accent;
    ctx.beginPath();
    ctx.arc(0, cy - 5, headWidth(ch) + 2, Math.PI * 1.01, Math.PI * 1.99);
    ctx.lineTo(headWidth(ch) + 2, cy - 2);
    ctx.lineTo(-headWidth(ch) - 2, cy - 2);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
    ctx.fillStyle = ch.hair;
    ctx.fillRect(-headWidth(ch), cy - 4, headWidth(ch) * 2, 4);
  } else if (ch.accessory === "visor") {
    ctx.fillStyle = ch.hair;
    ctx.beginPath();
    ctx.arc(0, cy - 4, headWidth(ch) + 1, Math.PI * 1.02, Math.PI * 1.98);
    ctx.lineTo(headWidth(ch) + 1, cy - 1);
    ctx.lineTo(-headWidth(ch) - 1, cy - 1);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
    ctx.fillStyle = ch.accent;
    roundRect(ctx, 4, cy - 7, 24, 5, 2.5);
    ctx.fill();
    ctx.stroke();
  } else if (ch.accessory === "headband") {
    ctx.fillStyle = ch.accent;
    ctx.fillRect(-headWidth(ch), cy - 6, headWidth(ch) * 2, 5);
    ctx.strokeRect(-headWidth(ch), cy - 6, headWidth(ch) * 2, 5);
  } else if (ch.accessory === "glasses") {
    ctx.fillStyle = "rgba(255,248,232,0.24)";
    ctx.beginPath();
    ctx.arc(-9, cy - 1, 8, 0, Math.PI * 2);
    ctx.fill();
    ctx.stroke();
    ctx.beginPath();
    ctx.arc(9, cy - 1, 8, 0, Math.PI * 2);
    ctx.fill();
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(-1, cy - 1);
    ctx.lineTo(1, cy - 1);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(17, cy - 1);
    ctx.lineTo(23, cy - 4);
    ctx.stroke();
  }
}
