/**
 * Esqueleto y poses del luchador chibi.
 *
 * Funciones puras: del estado del `Fighter` (que la simulación ya calcula)
 * salen las posiciones de pelvis, cabeza, pies y manos; rodillas y codos se
 * resuelven con IK de dos huesos. Nada aquí toca la simulación ni el canvas,
 * así que se puede testear y no afecta al online determinista.
 *
 * Sistema local (mirando a la derecha, +x = hacia delante):
 *   - origen = centro del luchador (f.x, f.y),
 *   - el suelo está en y = +34 (la planta del botín apoya ahí),
 *   - la cabeza queda alrededor de y = -15.
 */
import type { Fighter } from "./engine.ts";
import { JUMP } from "./constants.ts";

export const GROUND_Y = 34;
export const THIGH = 9.5;
export const SHIN = 9.5;
/** Del tobillo a la planta del botín. */
export const ANKLE_H = 4;
export const UPPER_ARM = 7.5;
export const FOREARM = 7;
const TORSO_LEN = 17;
/** Cabeza algo más arriba que el cuello: deja ver torso y brazos (proporción brawler chibi). */
const NECK_TO_HEAD = 18;

export type Vec = { x: number; y: number };
export type Limb = {
  root: Vec;
  joint: Vec;
  end: Vec;
};

export type FighterMood = "play" | "victory" | "defeat";
export type FaceMode = "normal" | "effort" | "stun" | "happy" | "sad";
export type Smear = "none" | "kick" | "flykick" | "stomp";

export type Pose = {
  /** Rotación de todo el cuerpo (voltereta, patada voladora) alrededor de `pivot`. */
  rot: number;
  pivot: Vec;
  pelvis: Vec;
  /** Inclinación del torso (+ = hacia delante). */
  lean: number;
  neck: Vec;
  head: Vec;
  headTilt: number;
  legB: Limb;
  legF: Limb;
  armB: Limb;
  armF: Limb;
  footRotB: number;
  footRotF: number;
  fistF: number;
  fistB: number;
  /** Botín delantero agrandado (impacto). */
  bigFoot: boolean;
  face: FaceMode;
  smear: Smear;
  /** El brazo trasero va por delante del pecho (balanceo hacia delante al correr). */
  backArmFront: boolean;
  /** 0..1: intensidad del golpe (estelas, destello del puño). */
  impact: number;
  /** Estiramiento visual vertical (salto) y aplastamiento (aterrizaje). */
  stretch: number;
  squash: number;
};

/** IK de dos huesos. Si el objetivo queda lejos, estira los huesos (dibujo animado) hasta `maxStretch`. */
export function solveLimb(
  root: Vec,
  target: Vec,
  l1: number,
  l2: number,
  bendDir: 1 | -1,
  maxStretch = 1.45,
): Limb {
  let dx = target.x - root.x;
  let dy = target.y - root.y;
  let d = Math.hypot(dx, dy) || 0.0001;
  let a = l1;
  let b = l2;
  const reach = a + b;
  if (d > reach * 0.999) {
    const s = Math.min(maxStretch, d / (reach * 0.999));
    a *= s;
    b *= s;
    if (d > (a + b) * 0.999) {
      const k = ((a + b) * 0.999) / d;
      dx *= k;
      dy *= k;
      d = (a + b) * 0.999;
    }
  }
  const minD = Math.abs(a - b) + 0.001;
  if (d < minD) d = minD;
  // Ley de cosenos: ángulo en la raíz entre la línea raíz→objetivo y el primer hueso.
  const cosA = (a * a + d * d - b * b) / (2 * a * d);
  const angA = Math.acos(Math.max(-1, Math.min(1, cosA)));
  const base = Math.atan2(dy, dx);
  const ang = base - bendDir * angA;
  const joint = { x: root.x + Math.cos(ang) * a, y: root.y + Math.sin(ang) * a };
  const end = { x: root.x + dx, y: root.y + dy };
  return { root, joint, end };
}

/** Sesgo del balanceo de brazos hacia delante (rad). */
const RUN_ARM_BIAS = 0.22;
/** Flexión del codo al correr (rad): ~90°, antebrazo hacia delante y arriba. */
const RUN_ELBOW = 1.3;

/**
 * Brazo de corredor por cinemática directa (sin IK, para que el codo nunca
 * salte de lado): brazo a `ang` de la vertical y antebrazo doblado
 * RUN_ELBOW hacia delante, con el codo siempre detrás de la mano.
 */
function runArm(shoulder: Vec, ang: number): Limb {
  const joint = { x: shoulder.x + Math.sin(ang) * UPPER_ARM, y: shoulder.y + Math.cos(ang) * UPPER_ARM };
  const fore = ang + RUN_ELBOW;
  const end = { x: joint.x + Math.sin(fore) * FOREARM, y: joint.y + Math.cos(fore) * FOREARM };
  return { root: shoulder, joint, end };
}

function ease(t: number): number {
  const c = Math.max(0, Math.min(1, t));
  return c * c * (3 - 2 * c);
}

function lerp(a: number, b: number, t: number): number {
  return a + (b - a) * t;
}

/** Punto a `len` del origen, girado `ang` desde la vertical hacia arriba (+ = hacia delante). */
function up(from: Vec, ang: number, len: number): Vec {
  return { x: from.x + Math.sin(ang) * len, y: from.y - Math.cos(ang) * len };
}

/**
 * Pose del luchador a partir de su estado. `reach` es el alcance real del
 * golpe (attackReach) para que el pie y el puño se dibujen donde pega la hitbox.
 */
export function poseFor(f: Fighter, time: number, mood: FighterMood, reach: number, shoulderW = 9.5): Pose {
  const air = !f.grounded;
  const airExtra = air && f.jumpsLeft === 0;
  const hover = f.hovering;
  const moving = f.grounded && Math.abs(f.vx) > 36 && f.atk === "idle" && f.stun <= 0;
  const speed = Math.min(1, Math.abs(f.vx) / 320);
  const stunned = f.stun > 0;
  const charging = f.charge > 0.05 && f.atk === "idle";
  const victory = mood === "victory";
  const defeat = mood === "defeat";
  const attacking = f.atk === "startup" || f.atk === "active" || f.atk === "recover";
  const flyKick = air && attacking;
  const charged = f.atkPower === "charged";

  // Valores por defecto: guardia relajada.
  let rot = 0;
  let pelvisX = 0;
  let pelvisY = 14;
  let lean = 0.04;
  let headTilt = 0;
  let footB: Vec = { x: -6.5, y: GROUND_Y };
  let footF: Vec = { x: 6.5, y: GROUND_Y };
  let footRotB = 0.04;
  let footRotF = -0.04;
  let handB: Vec = { x: -10, y: 14 };
  let handF: Vec = { x: 13, y: 14 };
  let fistF = 4.6;
  const fistB = 4.2;
  let bigFoot = false;
  let face: FaceMode = "normal";
  let smear: Smear = "none";
  let impact = 0;
  let stretch = 0;
  let planted = true;
  /** Ángulos del brazo (desde la vertical, + = hacia delante) durante la carrera. */
  let runArms: { front: number; back: number } | null = null;

  const idle = Math.sin(time * 3 + f.id * 1.7);

  if (moving) {
    // Ciclo de carrera: cada pie traza un óvalo (apoyo atrás, vuelo adelante).
    const p = f.anim * 12;
    const stride = 9 + speed * 4;
    const lift = 7 + speed * 3;
    const sF = Math.sin(p);
    const sB = Math.sin(p + Math.PI);
    footF = { x: 1 + sF * stride, y: GROUND_Y - Math.max(0, Math.cos(p)) * lift };
    footB = { x: -1 + sB * stride, y: GROUND_Y - Math.max(0, Math.cos(p + Math.PI)) * lift };
    footRotF = -Math.cos(p) * 0.45;
    footRotB = -Math.cos(p + Math.PI) * 0.45;
    // Brazos de atleta: codo a ~90°, el brazo oscila desde el hombro en
    // oposición a la pierna y el arco está sesgado HACIA DELANTE (la mano
    // sube a la altura del pecho delante y apenas pasa la cadera atrás).
    const swing = 0.7 + speed * 0.2;
    runArms = { front: RUN_ARM_BIAS - sF * swing, back: RUN_ARM_BIAS - sB * swing };
    lean = 0.16 + speed * 0.12;
    pelvisY = 14 - Math.abs(Math.cos(p)) * 1.4;
    pelvisX = 1;
    headTilt = 0.05 + Math.sin(p * 2) * 0.03;
  } else if (f.grounded && !attacking && !stunned) {
    // Respiración: hombros arriba/abajo, pies quietos.
    pelvisY = 14 + Math.max(0, idle) * 0.6;
    handF = { x: 13, y: 14 + idle * 0.8 };
    handB = { x: -10, y: 14 + idle * 0.8 };
  }

  if (air && !flyKick && f.atk !== "stomp") {
    planted = false;
    const rising = f.vy < 0;
    stretch = Math.max(-0.12, Math.min(0.2, -f.vy / 1800));
    if (rising) {
      footB = { x: -7, y: 25 };
      footF = { x: 7, y: 23 };
      handB = { x: -15, y: -1 };
      handF = { x: 13, y: -3 };
    } else {
      footB = { x: -8, y: 31 };
      footF = { x: 8, y: 30 };
      handB = { x: -17, y: 4 };
      handF = { x: 16, y: 3 };
    }
    footRotB = 0.35;
    footRotF = -0.3;
    if (airExtra && rising) {
      // Doble salto: voltereta hacia delante en bolita, de -620 a 0 de vy.
      const t = 1 - Math.min(1, -f.vy / -JUMP.secondVy);
      rot = ease(t) * Math.PI * 2;
      footB = { x: -4, y: 22 };
      footF = { x: 6, y: 20 };
      handB = { x: -6, y: 15 };
      handF = { x: 8, y: 14 };
      stretch = 0;
    }
    if (hover) {
      const flap = Math.sin(time * 18);
      footB = { x: -6, y: 32 };
      footF = { x: 6, y: 31 };
      handB = { x: -19, y: 2 + flap * 3 };
      handF = { x: 19, y: 1 - flap * 3 };
    }
  }

  if (charging) {
    const c = Math.min(1, f.charge);
    pelvisY = 15.5 + c * 3;
    lean = -0.12;
    footB = { x: -9, y: GROUND_Y };
    footF = { x: 8, y: GROUND_Y };
    handF = { x: -2, y: 2 };
    handB = { x: -14, y: 6 };
    fistF = 5.5 + c;
    face = "effort";
  }

  if (attacking && !flyKick) {
    face = "effort";
    if (f.atk === "startup") {
      // Anticipación: se agacha, recoge la rodilla y lleva el puño atrás.
      const need = charged ? 0.08 : 0.04;
      const t = ease(f.atkT / need);
      pelvisY = lerp(14, 16.5, t);
      lean = lerp(0.04, -0.16, t);
      footB = { x: -8, y: GROUND_Y };
      footF = { x: lerp(6, 3, t), y: lerp(GROUND_Y, 22, t) };
      footRotF = -0.5;
      handF = { x: lerp(12, -6, t), y: lerp(11, 4, t) };
      handB = { x: lerp(-11, 6, t), y: lerp(12, 4, t) };
      fistF = 5;
    } else if (f.atk === "active") {
      // Golpe COMBINADO: patada al frente y puñetazo a la vez, con estocada.
      const dur = charged ? 0.12 : 0.09;
      const t = ease(f.atkT / (dur * 0.45));
      pelvisX = lerp(0, 5, t);
      pelvisY = 15;
      lean = lerp(-0.1, 0.22, t);
      footB = { x: -9, y: GROUND_Y };
      footF = { x: lerp(8, reach - 6, t), y: lerp(24, 14, t) };
      footRotF = -1.35;
      handF = { x: lerp(4, reach - 10, t), y: lerp(4, -1, t) };
      handB = { x: -13, y: 4 };
      fistF = charged ? 7.2 : 6.2;
      bigFoot = true;
      smear = "kick";
      impact = t;
      headTilt = 0.08;
    } else {
      // Recuperación: vuelve a guardia.
      const t = ease(f.atkT / 0.14);
      pelvisX = lerp(5, 0, t);
      lean = lerp(0.18, 0.04, t);
      footB = { x: -8, y: GROUND_Y };
      footF = { x: lerp(reach - 12, 7, t), y: lerp(20, GROUND_Y, t) };
      footRotF = lerp(-0.9, 0, t);
      handF = { x: lerp(reach - 16, 12, t), y: lerp(2, 11, t) };
      handB = { x: -12, y: 8 };
      fistF = lerp(5.6, 4.6, t);
    }
  }

  if (flyKick) {
    // Patada voladora: cuerpo inclinado hacia atrás, pierna delantera recta
    // apuntando al balón, la trasera recogida y los brazos atrás.
    planted = false;
    face = "effort";
    let t = 1;
    if (f.atk === "startup") t = ease(f.atkT / (charged ? 0.08 : 0.04)) * 0.6;
    else if (f.atk === "recover") t = 1 - ease(f.atkT / 0.14) * 0.7;
    rot = lerp(0, -0.42, t);
    lean = lerp(0, -0.12, t);
    footF = { x: lerp(8, reach - 2, t), y: lerp(26, 12, t) };
    footRotF = lerp(-0.3, -1.45, t);
    footB = { x: lerp(-7, -2, t), y: lerp(28, 22, t) };
    footRotB = 0.9;
    handF = { x: lerp(14, -4, t), y: lerp(2, -6, t) };
    handB = { x: lerp(-15, -19, t), y: lerp(2, -3, t) };
    bigFoot = f.atk === "active";
    smear = f.atk === "active" ? "flykick" : "none";
    impact = f.atk === "active" ? 1 : 0;
  }

  if (f.atk === "stomp") {
    planted = false;
    face = "effort";
    rot = 0.1;
    lean = 0.2;
    footB = { x: -5, y: 40 };
    footF = { x: 6, y: 40 };
    footRotB = 0;
    footRotF = 0;
    handB = { x: -17, y: -6 };
    handF = { x: 17, y: -7 };
    smear = "stomp";
  }

  if (stunned) {
    face = "stun";
    lean = Math.sin(time * 20) * 0.13;
    headTilt = Math.sin(time * 17) * 0.16;
    handB = { x: -12, y: 18 };
    handF = { x: 14, y: 18 };
  }
  if (victory) {
    face = "happy";
    const hop = Math.max(0, Math.sin(time * 8));
    pelvisY = 14 - hop * 2;
    handB = { x: -23, y: -20 - hop * 2 };
    handF = { x: 25, y: -22 - hop * 2 };
    headTilt = Math.sin(time * 8) * 0.06;
  }
  if (defeat) {
    face = "sad";
    lean = 0.18;
    pelvisY = 16;
    headTilt = 0.2;
    handB = { x: -9, y: 22 };
    handF = { x: 9, y: 22 };
  }

  // En el suelo, el pie más bajo apoya EXACTAMENTE en el suelo (sin flotar).
  if (planted && f.grounded) {
    const low = Math.max(footB.y, footF.y);
    if (low < GROUND_Y) {
      footB = { x: footB.x, y: footB.y + (GROUND_Y - low) };
      footF = { x: footF.x, y: footF.y + (GROUND_Y - low) };
    }
  }

  const pelvis = { x: pelvisX, y: pelvisY };
  const neck = up(pelvis, lean, TORSO_LEN);
  const head = up(neck, lean * 0.6 + headTilt, NECK_TO_HEAD);
  const shoulderB = up(pelvis, lean, TORSO_LEN - 3);
  const shoulderF = up(pelvis, lean, TORSO_LEN - 3);
  // Vista 3/4: el hombro delantero va hacia el borde del pecho, el trasero queda medio oculto.
  shoulderB.x -= shoulderW * 0.6;
  shoulderF.x += shoulderW * 0.8;
  let runLimbF: Limb | null = null;
  let runLimbB: Limb | null = null;
  if (runArms) {
    // Cinemática directa: el ángulo del brazo se suma a la inclinación del torso.
    runLimbF = runArm(shoulderF, runArms.front + lean * 0.5);
    runLimbB = runArm(shoulderB, runArms.back + lean * 0.5);
  }

  const hipB = { x: pelvis.x - 4, y: pelvis.y + 1.5 };
  const hipF = { x: pelvis.x + 4, y: pelvis.y + 1.5 };
  const ankleB = { x: footB.x, y: footB.y - ANKLE_H };
  const ankleF = { x: footF.x, y: footF.y - ANKLE_H };

  return {
    rot,
    pivot: { x: 0, y: 8 },
    pelvis,
    lean,
    neck,
    head,
    headTilt,
    // Las rodillas se doblan hacia delante; los codos hacia atrás/abajo.
    legB: solveLimb(hipB, ankleB, THIGH, SHIN, 1),
    legF: solveLimb(hipF, ankleF, THIGH, SHIN, 1, smear === "kick" || smear === "flykick" ? 1.6 : 1.3),
    armB: runLimbB ?? solveLimb(shoulderB, handB, UPPER_ARM, FOREARM, -1),
    armF: runLimbF ?? solveLimb(shoulderF, handF, UPPER_ARM, FOREARM, -1, impact > 0 ? 1.9 : 1.35),
    footRotB,
    footRotF,
    fistF,
    fistB,
    bigFoot,
    face,
    smear,
    backArmFront: !!runArms && runArms.back > RUN_ARM_BIAS + 0.12,
    impact,
    stretch,
    squash: f.landSquash,
  };
}
