/**
 * Online 1 vs 1 para Goal Fighters: lockstep por pasos sobre WebRTC (PeerJS).
 *
 * Idea: el motor ya es determinista (misma semilla + mismos pads = mismo
 * partido, paso a paso; ver rng.ts). Así que los dos navegadores corren la
 * MISMA simulación y solo se intercambian los pads:
 *
 * - Cada frame, cada lado muestrea su pad y envía un paquete {from, n, pad}
 *   que cubre los pasos [from, from+n). El pad lleva los bordes (jumpPressed
 *   y demás) tal como los calcula el componente; el receptor aplica el pad
 *   completo en el primer paso del paquete y stripEdges en el resto, igual
 *   que el bucle local. El motor no se toca.
 * - Cada lado ejecuta el paso S solo cuando tiene el pad local Y el remoto
 *   para S. Si el paquete remoto tarda, el partido se congela un instante en
 *   los dos lados (sin desincronizar): el retraso efectivo es medio RTT.
 * - Si un lado corre más rápido enviando, el otro lo alcanza; si la brecha
 *   supera 2 s, el emisor deja de enviar hasta que el partido lo alcance.
 * - Cada 120 pasos (1 s) los dos lados intercambian un hash del estado. Si
 *   no coinciden, el anfitrión manda una foto completa del partido y el
 *   invitado la adopta. Es el seguro por si algo se desvía.
 *
 * Señalización: PeerJS cloud (gratis, sin cuenta ni claves). El anfitrión
 * crea la sala con un código de 4 letras; el invitado se conecta a ese
 * código. El juego sigue siendo estático en Netlify: no hay servidor propio.
 * p2p.ts (la capa WebRTC de la plantilla Grok) NO se usa: necesita un
 * servidor /api/rtc que no existe. PeerJS lo reemplaza entero.
 *
 * Espectadores: el anfitrión acepta varios pares. El primero juega; el
 * resto mira el partido en vivo: el anfitrión les reenvía los pads de los
 * dos jugadores etiquetados por lado (`pad` con `side`) y el espectador
 * simula la misma partida con `receiveSidePad` (sin mandar nada). El
 * espectador puede pedir turno; al terminar el partido, si hay cola, el
 * retador juega contra el ganador y el perdedor baja a espectador. Como
 * todos siguen conectados al anfitrión, rotar es solo cambiar roles: la
 * siguiente partida arranca sin reconectar a nadie. Solo el anfitrión manda
 * hashes (difundidos a todos); cada par se detecta solo y pide la foto.
 */

import {
  blankPad,
  createMatch,
  stepMatch,
  stripEdges,
  type InputPad,
  type Match,
  type MatchCharacters,
} from "../../game/engine.ts";
import type { CharacterId } from "../../game/characters.ts";
import { STEP } from "../../game/constants.ts";

/* ------------------------------------------------------------------ */
/* Sala y códigos                                                      */
/* ------------------------------------------------------------------ */

const CODE_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"; // sin 0/O/1/I/L

/** Código de sala de 4 letras, legible por teléfono. */
export function makeRoomCode(): string {
  const buf = new Uint32Array(4);
  crypto.getRandomValues(buf);
  let code = "";
  for (let i = 0; i < 4; i++) code += CODE_ALPHABET[buf[i] % CODE_ALPHABET.length];
  return code;
}

export function roomPeerId(code: string): string {
  return `goalfighters-${code.trim().toLowerCase()}`;
}

export function isRoomCode(code: string): boolean {
  return /^[A-HJ-KM-NP-Z2-9]{4}$/i.test(code.trim());
}

/**
 * Enlace de invitación a una sala: quien lo abre entra directo, sin
 * escribir el código. `base` es la URL actual (por defecto, la de la
 * página); se pasa explícita en los tests para no depender de window.
 */
export function roomInviteLink(code: string, base?: string): string {
  const href =
    base ?? (typeof window !== "undefined" ? window.location.href : "https://goalfighters.netlify.app/");
  const url = new URL(href);
  url.searchParams.set("room", code.trim().toUpperCase());
  url.hash = "";
  return url.toString();
}

/** Código de sala que trae la URL (?room=XXXX), o null si no hay o no vale. */
export function roomCodeFromSearch(search: string): string | null {
  const raw = new URLSearchParams(search).get("room");
  if (!raw) return null;
  const code = raw.trim().toUpperCase();
  return isRoomCode(code) ? code : null;
}

/* ------------------------------------------------------------------ */
/* Mensajes por el cable (JSON)                                        */
/* ------------------------------------------------------------------ */

/**
 * Rol de un par en la sala: "player" juega el partido, "spectator" lo mira
 * en vivo y puede pedir turno. El anfitrión asigna el rol al conectar: la
 * primera conexión (o las dos primeras, si el anfitrión especta) juega.
 */
export type PeerRole = "player" | "spectator";

/** Lado de un jugador dentro del partido (null = espectador, no controla a nadie). */
export type MatchSide = "p0" | "p1" | null;

/** Entrada de la cola de turnos: quién espera y con qué luchador. */
export type QueueEntry = { id: string; char: CharacterId };

export type NetMsg =
  | { t: "hello"; name: string; char: CharacterId }
  | { t: "start"; seed: number; left: CharacterId; right: CharacterId; you: "p0" | "p1" | "spectator" }
  | { t: "pad"; from: number; n: number; pad: InputPad; side?: "p0" | "p1" }
  | { t: "hash"; step: number; hash: string }
  | { t: "snapshot"; step: number; state: MatchState }
  | { t: "needstate" }
  | { t: "rematch" }
  | { t: "bye" }
  | { t: "role"; role: PeerRole }
  | { t: "request-turn"; char: CharacterId }
  | { t: "cancel-turn" }
  | { t: "queue"; entries: QueueEntry[] }
  | { t: "match-end"; leaver: string }
  | { t: "ping"; at: number }
  | { t: "pong"; at: number };

/** Sufijo corto de un peer id, para mostrarlo en la cola («Mango · 7K2P»). */
export function shortPeerId(id: string): string {
  const clean = id.replace(/[^a-zA-Z0-9]/g, "");
  return clean.slice(-4).toUpperCase() || "????";
}

/* ------------------------------------------------------------------ */
/* Cola de turnos y rotación (lógica pura, propiedad del anfitrión)    */
/* ------------------------------------------------------------------ */

/** Añadir a la cola (por orden de llegada; un duplicado se ignora). */
export function queueAdd(q: QueueEntry[], e: QueueEntry): QueueEntry[] {
  if (q.some((x) => x.id === e.id)) return q;
  return [...q, e];
}

/** Sacar de la cola (al cancelar, al entrar a jugar o al irse de la sala). */
export function queueRemove(q: QueueEntry[], id: string): QueueEntry[] {
  return q.filter((x) => x.id !== id);
}

export type Rotation = {
  winnerSide: "p0" | "p1";
  loserSide: "p0" | "p1";
  challenger: QueueEntry;
  /** Cola sin el retador. */
  rest: QueueEntry[];
};

/**
 * Quién juega la siguiente partida: el ganador se queda, el retador toma el
 * lado del perdedor. Devuelve null sin cola o sin ganador (el gol de oro
 * garantiza que siempre hay uno; el empate solo se cubre por defensa).
 */
export function nextRotation(scoreL: number, scoreR: number, q: QueueEntry[]): Rotation | null {
  if (q.length === 0 || scoreL === scoreR) return null;
  const winnerSide = scoreL > scoreR ? "p0" : "p1";
  const loserSide = winnerSide === "p0" ? "p1" : "p0";
  const [challenger, ...rest] = q;
  return { winnerSide, loserSide, challenger, rest };
}

/* ------------------------------------------------------------------ */
/* Conexión PeerJS (import dinámico: fuera del SSR y del bundle inicial) */
/* ------------------------------------------------------------------ */

export type NetStatus =
  | "idle"
  | "creating"
  | "waiting"
  | "joining"
  | "connected"
  | "closed"
  | "error";

/**
 * Opciones del servidor de señalización. Sin variables de entorno, la nube
 * PeerJS (gratis, sin cuenta). Para pruebas locales: VITE_PEERJS_HOST,
 * VITE_PEERJS_PORT, VITE_PEERJS_PATH y VITE_PEERJS_SECURE.
 */
function peerOptions() {
  const host = import.meta.env.VITE_PEERJS_HOST as string | undefined;
  if (!host) return undefined;
  return {
    host,
    port: Number(import.meta.env.VITE_PEERJS_PORT ?? 9000),
    path: (import.meta.env.VITE_PEERJS_PATH as string | undefined) ?? "/",
    secure: import.meta.env.VITE_PEERJS_SECURE === "true",
    // Pruebas locales (VITE_PEERJS_NO_STUN=true): sin STUN de Google
    // (inaccesible en la sandbox), solo candidatos de la red local. En
    // producción no se define y PeerJS usa sus STUN por defecto.
    ...(import.meta.env.VITE_PEERJS_NO_STUN === "true" ? { config: { iceServers: [] } } : {}),
  };
}

/** Errores de la señalización que suelen ser pasajeros (pestaña en segundo plano, red que parpadea). */
function isTransientSignalError(type?: string): boolean {
  return type === "network" || type === "socket-error" || type === "socket-closed" || type === "server-error";
}

const MAX_SIGNAL_FAILS = 6;

interface PeerSlot {
  conn: import("peerjs").DataConnection;
  role: PeerRole;
  rttAvg: number;
  jitterAvg: number;
}

/**
 * Conexión PeerJS de la sala. El anfitrión acepta VARIOS pares: el primero
 * (o los dos primeros, si el anfitrión especta) juega y el resto mira como
 * espectador. El invitado tiene una sola conexión (con el anfitrión).
 * Cada mensaje llega con su remitente (`onMessage(msg, from)`) para que el
 * anfitrión enrute pads, peticiones y fotos al par que corresponde.
 */
export class OnlineNet {
  onMessage: ((msg: NetMsg, from: string) => void) | null = null;
  onStatus: ((s: NetStatus, detail?: string) => void) | null = null;
  onRtt: ((ms: number, from: string) => void) | null = null;
  /** RTT suavizado y jitter (ms) de UN par, para ajustar el retraso de entrada. */
  onLatency: ((rttMs: number, jitterMs: number, from: string) => void) | null = null;
  /** Un par se conectó o se fue (el anfitrión reacciona: roles, cola). */
  onPeersChanged: (() => void) | null = null;

  private peer: import("peerjs").Peer | null = null;
  /** Anfitrión: un slot por par. Invitado: un solo slot (el anfitrión). */
  private peers = new Map<string, PeerSlot>();
  private pingTimer: ReturnType<typeof setInterval> | null = null;
  private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
  private closed = false;
  /** Fallos seguidos de la señalización del anfitrión (se reinicia al reabrir). */
  private signalFails = 0;
  private isHost = false;
  /** Jugadores remotos máximos (el anfitrión lo fija: 1 si juega, 2 si especta). */
  maxRemotePlayers = 1;

  /** El peer sigue registrado en el servidor de señalización. */
  get registered(): boolean {
    const p = this.peer as unknown as { disconnected?: boolean; destroyed?: boolean } | null;
    return !!p && !p.disconnected && !p.destroyed;
  }

  /**
   * Volver a registrar el id de la sala tras perder la señalización.
   * El móvil cierra el socket cuando la pestaña pasa a segundo plano
   * (al compartir por WhatsApp); sin esto la sala deja de existir.
   */
  reconnect(): void {
    const p = this.peer;
    if (!p || this.closed) return;
    try {
      if (p.disconnected) p.reconnect();
    } catch {
      /* el próximo intento lo cubre el visible */
    }
  }

  private scheduleReconnect(): void {
    if (this.closed || this.reconnectTimer) return;
    this.reconnectTimer = setTimeout(() => {
      this.reconnectTimer = null;
      this.reconnect();
    }, 500);
  }

  /** Anfitrión: registra el id de la sala y espera a que entre el rival. */
  async createRoom(code: string): Promise<void> {
    const { Peer } = await import("peerjs");
    this.teardown();
    this.closed = false;
    this.isHost = true;
    this.setStatus("creating");
    this.peer = new Peer(roomPeerId(code), peerOptions());
    this.signalFails = 0;
    this.peer.on("open", () => {
      this.signalFails = 0;
      this.setStatus("waiting");
    });
    this.peer.on("connection", (c) => this.attachHost(c));
    this.peer.on("disconnected", () => this.scheduleReconnect());
    this.peer.on("error", (err: { type?: string }) => {
      if (this.closed) return;
      if (err?.type === "unavailable-id") {
        this.setStatus("error", "taken");
      } else if (isTransientSignalError(err?.type) && this.peers.size === 0 && this.signalFails < MAX_SIGNAL_FAILS) {
        // Al compartir por WhatsApp el móvil duerme el navegador y se corta
        // el socket con el servidor: PeerJS lo reporta como error "network".
        // No es un problema de internet: se reintenta en silencio y, si de
        // verdad no hay forma, recién después de varios intentos se avisa.
        this.signalFails++;
        this.scheduleReconnect();
      } else {
        this.setStatus("error", err?.type ?? "peer");
      }
    });
  }

  /** Invitado: se conecta al id de la sala. */
  async joinRoom(code: string): Promise<void> {
    const { Peer } = await import("peerjs");
    this.teardown();
    this.closed = false;
    this.isHost = false;
    this.setStatus("joining");
    this.peer = new Peer(peerOptions() ?? {});
    this.peer.on("open", () => {
      const c = this.peer!.connect(roomPeerId(code), { reliable: true });
      this.attachJoiner(c);
    });
    // El invitado no acepta conexiones entrantes: todo pasa por el anfitrión.
    this.peer.on("connection", (c) => {
      try {
        c.close();
      } catch {
        /* ya cerrada */
      }
    });
    this.peer.on("disconnected", () => this.scheduleReconnect());
    this.peer.on("error", (err: { type?: string }) => {
      if (err?.type === "peer-unavailable") this.setStatus("error", "not-found");
      else if (!this.closed) this.setStatus("error", err?.type ?? "peer");
    });
  }

  /** Jugadores remotos conectados ahora mismo (anfitrión). */
  remotePlayers(): number {
    let n = 0;
    for (const s of this.peers.values()) if (s.role === "player") n++;
    return n;
  }

  peerRole(peerId: string): PeerRole | null {
    return this.peers.get(peerId)?.role ?? null;
  }

  /** Pares conectados (id + rol), para la vista de la sala. */
  peersList(): Array<{ id: string; role: PeerRole }> {
    return [...this.peers.entries()].map(([id, s]) => ({ id, role: s.role }));
  }

  playerIds(): string[] {
    return [...this.peers.entries()].filter(([, s]) => s.role === "player").map(([id]) => id);
  }

  spectatorIds(): string[] {
    return [...this.peers.entries()].filter(([, s]) => s.role === "spectator").map(([id]) => id);
  }

  /** Cambiar el rol de un par (rotación: el retador sube, el perdedor baja). */
  setRole(peerId: string, role: PeerRole): void {
    const slot = this.peers.get(peerId);
    if (!slot || slot.role === role) return;
    slot.role = role;
    this.onPeersChanged?.();
  }

  /** Id del anfitrión (invitado), o null si aún no hay conexión. */
  get hostId(): string | null {
    if (this.isHost) return null;
    const first = this.peers.keys().next();
    return first.done ? null : first.value;
  }

  /** Mi propio peer id (para buscarme en la cola), o null antes de abrir. */
  get myId(): string | null {
    return this.peer?.id ?? null;
  }

  /**
   * Anfitrión: un par entrante. El primero (o los dos primeros, si el
   * anfitrión especta) juega; el resto mira. Al abrirse el canal se le
   * manda su rol; el componente reacciona con onPeersChanged (foto del
   * partido en curso, cola).
   */
  private attachHost(c: import("peerjs").DataConnection): void {
    const role: PeerRole = this.remotePlayers() < this.maxRemotePlayers ? "player" : "spectator";
    const slot: PeerSlot = { conn: c, role, rttAvg: 0, jitterAvg: 0 };
    this.peers.set(c.peer, slot);
    c.on("open", () => {
      this.sendTo(c.peer, { t: "role", role });
      this.startPing();
      // Solo un jugador cambia el estado de la sala: un espectador no
      // arranca el partido y la vista de espera sigue esperando al rival.
      if (role === "player") this.setStatus("connected");
      this.onPeersChanged?.();
    });
    c.on("data", (d) => this.handleData(c.peer, slot, d));
    c.on("close", () => {
      const wasPlayer = this.peers.get(c.peer)?.role === "player";
      this.peers.delete(c.peer);
      if (this.peers.size === 0) this.stopPing();
      if (!this.closed && wasPlayer) this.setStatus("closed", c.peer);
      this.onPeersChanged?.();
    });
    c.on("error", () => {
      if (this.closed) return;
      // Un espectador con problemas no tumba la sala: se suelta en silencio.
      if (this.peers.get(c.peer)?.role === "player") this.setStatus("error", "conn");
      else this.onPeersChanged?.();
    });
  }

  /** Invitado: la única conexión, con el anfitrión. */
  private attachJoiner(c: import("peerjs").DataConnection): void {
    // El rol del slot no se usa en el invitado (su rol lo asigna el
    // anfitrión con el mensaje `role`); se guarda "player" por defecto.
    const slot: PeerSlot = { conn: c, role: "player", rttAvg: 0, jitterAvg: 0 };
    this.peers.set(c.peer, slot);
    c.on("open", () => {
      this.setStatus("connected");
      this.startPing();
      this.onPeersChanged?.();
    });
    c.on("data", (d) => this.handleData(c.peer, slot, d));
    c.on("close", () => {
      this.peers.delete(c.peer);
      this.stopPing();
      if (!this.closed) this.setStatus("closed");
      this.onPeersChanged?.();
    });
    c.on("error", () => {
      if (!this.closed) this.setStatus("error", "conn");
    });
  }

  private handleData(from: string, slot: PeerSlot, d: unknown): void {
    const msg = d as NetMsg;
    if (msg?.t === "ping") {
      this.sendTo(from, { t: "pong", at: msg.at });
      return;
    }
    if (msg?.t === "pong") {
      const rtt = Math.max(0, Date.now() - msg.at);
      this.onRtt?.(rtt, from);
      if (slot.rttAvg === 0) {
        slot.rttAvg = rtt;
      } else {
        // Media móvil del RTT y de su desviación (como el RTO de TCP).
        slot.jitterAvg += (Math.abs(rtt - slot.rttAvg) - slot.jitterAvg) * 0.25;
        // Los picos suben rápido (hay que reaccionar) y bajan despacio.
        slot.rttAvg += (rtt - slot.rttAvg) * (rtt > slot.rttAvg ? 0.5 : 0.15);
      }
      this.onLatency?.(slot.rttAvg, slot.jitterAvg, from);
      return;
    }
    this.onMessage?.(msg, from);
  }

  /** Última medición de red de UN par (RTT suavizado y jitter, en ms). */
  latencyFor(peerId: string): { rtt: number; jitter: number } | null {
    const s = this.peers.get(peerId);
    return s && s.rttAvg > 0 ? { rtt: s.rttAvg, jitter: s.jitterAvg } : null;
  }

  /**
   * Última medición de red (RTT suavizado y jitter, en ms), si ya hay:
   * la del primer jugador remoto (anfitrión) o la del anfitrión (invitado).
   */
  get latency(): { rtt: number; jitter: number } | null {
    const first = this.playerIds()[0] ?? this.peers.keys().next().value;
    return first ? this.latencyFor(first) : null;
  }

  private startPing(): void {
    if (this.pingTimer) return;
    // Primera medición ya, no a los 0,5 s: así, cuando empieza el partido,
    // el retraso de entrada ya conoce la red.
    this.broadcast({ t: "ping", at: Date.now() });
    // Cada 0,5 s: con 2 s, un pico de latencia tardaba demasiado en notarse
    // y el partido se congelaba antes de que el retraso de entrada subiera.
    this.pingTimer = setInterval(() => {
      this.broadcast({ t: "ping", at: Date.now() });
    }, 500);
  }

  private stopPing(): void {
    if (this.pingTimer) clearInterval(this.pingTimer);
    this.pingTimer = null;
  }

  /** Anfitrión: mandar a un par concreto. */
  sendTo(peerId: string, msg: NetMsg): void {
    const slot = this.peers.get(peerId);
    if (slot?.conn.open) slot.conn.send(msg);
  }

  /** Invitado: mandar al anfitrión (el anfitrión no lo usa). */
  sendToHost(msg: NetMsg): void {
    if (this.isHost) return;
    for (const slot of this.peers.values()) {
      if (slot.conn.open) slot.conn.send(msg);
    }
  }

  /** Anfitrión: mandar a todos los jugadores remotos. */
  sendToPlayers(msg: NetMsg): void {
    for (const slot of this.peers.values()) {
      if (slot.role === "player" && slot.conn.open) slot.conn.send(msg);
    }
  }

  /** Anfitrión: mandar a todos los espectadores. */
  sendToSpectators(msg: NetMsg): void {
    for (const slot of this.peers.values()) {
      if (slot.role === "spectator" && slot.conn.open) slot.conn.send(msg);
    }
  }

  /** Mandar a todos los pares conectados. */
  broadcast(msg: NetMsg): void {
    for (const slot of this.peers.values()) {
      if (slot.conn.open) slot.conn.send(msg);
    }
  }

  get connected(): boolean {
    for (const slot of this.peers.values()) if (slot.conn.open) return true;
    return false;
  }

  private setStatus(s: NetStatus, detail?: string): void {
    this.onStatus?.(s, detail);
  }

  close(): void {
    // Soltar los callbacks: cualquier evento tardío del peer que se está
    // destruyendo ya no puede llegar a la interfaz (mensajes de error al
    // pulsar Cancelar).
    this.onStatus = null;
    this.onMessage = null;
    this.onRtt = null;
    this.onLatency = null;
    this.onPeersChanged = null;
    this.teardown();
  }

  /** Cierra peer y conexiones SIN soltar los callbacks (createRoom/joinRoom los necesitan). */
  private teardown(): void {
    this.closed = true;
    this.stopPing();
    if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
    this.reconnectTimer = null;
    for (const slot of this.peers.values()) {
      try {
        slot.conn.close();
      } catch {
        /* ya cerrada */
      }
    }
    this.peers.clear();
    try {
      this.peer?.destroy();
    } catch {
      /* ya destruido */
    }
    this.peer = null;
  }
}

/* ------------------------------------------------------------------ */
/* Hash de sincronía                                                   */
/* ------------------------------------------------------------------ */

function r2(n: number): number {
  return Math.round(n * 100) / 100;
}

/**
 * Huella del estado que decide el futuro del partido. Redondeada a 0,01
 * para tolerar el último bit de coma flotante entre navegadores. Las
 * partículas, los textos, el shake y la cámara son solo visuales y no
 * entran: no afectan a la simulación. La mente del bot tampoco: en online
 * los dos luchadores son humanos y su mente nunca cambia.
 */
export function stateHash(m: Match): string {
  const f = m.fighters
    .map((p) =>
      [
        r2(p.x),
        r2(p.y),
        r2(p.vx),
        r2(p.vy),
        p.facing,
        p.grounded ? 1 : 0,
        p.jumpsLeft,
        p.atk,
        Math.round(p.atkT * 1000),
        Math.round(p.stun * 1000),
        Math.round(p.charge * 1000),
        p.hitBall ? 1 : 0,
      ].join(","),
    )
    .join("|");
  const b = [
    r2(m.ball.x),
    r2(m.ball.y),
    r2(m.ball.vx),
    r2(m.ball.vy),
    Math.round(m.ball.flame * 100),
  ].join(",");
  // Power-up: la burbuja, el ítem y los escudos mueven el balón, así que entran
  // en el hash (si un peer diverge en un disco, el desync se detecta).
  const pw = [
    m.bubble ? [1, r2(m.bubble.x), r2(m.bubble.y), Math.round(m.bubble.bobT * 1000), Math.round(m.bubble.ttl * 1000)].join(",") : "0",
    m.item ? [1, r2(m.item.x), r2(m.item.y), Math.round(m.item.ttl * 1000)].join(",") : "0",
    m.shields.left ? [1, Math.round(m.shields.left.t * 1000)].join(",") : "0",
    m.shields.right ? [1, Math.round(m.shields.right.t * 1000)].join(",") : "0",
    Math.round(m.nextBubbleIn * 1000),
  ].join("|");
  const s = [
    f,
    b,
    pw,
    m.scoreL,
    m.scoreR,
    Math.round(m.time * 1000),
    m.phase,
    Math.round(m.timer * 1000),
    Math.round(m.kickoffGrace * 1000),
    m.rng.s,
  ].join(";");

  let h = 0x811c9dc5;
  for (let i = 0; i < s.length; i++) {
    h ^= s.charCodeAt(i);
    h = Math.imul(h, 0x01000193);
  }
  return (h >>> 0).toString(16);
}

/* ------------------------------------------------------------------ */
/* Foto completa del partido (resync)                                  */
/* ------------------------------------------------------------------ */

export type MatchState = ReturnType<typeof snapshotMatch>;

export function snapshotMatch(m: Match) {
  return {
    time: m.time,
    timer: m.timer,
    sudden: m.sudden,
    grace: m.grace,
    kickoffGrace: m.kickoffGrace,
    pendingOver: m.pendingOver,
    scoreL: m.scoreL,
    scoreR: m.scoreR,
    phase: m.phase,
    hitstop: m.hitstop,
    ownGoal: m.ownGoal,
    lastTouch: m.lastTouch ? { ...m.lastTouch } : null,
    banner: m.banner,
    subtitle: m.subtitle,
    rngS: m.rng.s,
    ball: { ...m.ball },
    fighters: m.fighters.map((p) => ({
      ...p,
      hitIds: [...p.hitIds],
      mind: { ...p.mind },
    })),
    // Power-up: sin esto, el restaurado divergía en cuanto había una burbuja
    // o un escudo (el hash sí los cubre, así que la foto debe cubrirlos).
    bubble: m.bubble ? { ...m.bubble } : null,
    item: m.item ? { ...m.item } : null,
    shields: {
      left: m.shields.left ? { ...m.shields.left } : null,
      right: m.shields.right ? { ...m.shields.right } : null,
    },
    nextBubbleIn: m.nextBubbleIn,
  };
}

export function restoreMatch(m: Match, s: MatchState): void {
  m.time = s.time;
  m.timer = s.timer;
  m.sudden = s.sudden;
  m.grace = s.grace;
  m.kickoffGrace = s.kickoffGrace;
  m.pendingOver = s.pendingOver;
  m.scoreL = s.scoreL;
  m.scoreR = s.scoreR;
  m.phase = s.phase;
  m.hitstop = s.hitstop;
  m.ownGoal = s.ownGoal;
  m.lastTouch = s.lastTouch ? { ...s.lastTouch } : null;
  m.banner = s.banner;
  m.subtitle = s.subtitle;
  m.rng.s = s.rngS;
  m.bubble = s.bubble ? { ...s.bubble } : null;
  m.item = s.item ? { ...s.item } : null;
  m.shields.left = s.shields.left ? { ...s.shields.left } : null;
  m.shields.right = s.shields.right ? { ...s.shields.right } : null;
  m.nextBubbleIn = s.nextBubbleIn;
  Object.assign(m.ball, s.ball);
  for (let i = 0; i < m.fighters.length; i++) {
    const dst = m.fighters[i];
    const src = s.fighters[i];
    if (!src) continue;
    Object.assign(dst, src, { hitIds: [...src.hitIds], mind: { ...src.mind } });
  }
}

/* ------------------------------------------------------------------ */
/* Sesión lockstep                                                     */
/* ------------------------------------------------------------------ */

const HASH_EVERY = 120; // pasos (1 s)
const MAX_GAP = 240; // pasos (2 s): freno si el rival se queda atrás
const MAX_STEPS_PER_FRAME = 12;
// Retraso de entrada (pasos, ~67 ms a 120 Hz): el partido simula con este
// margen detrás de lo enviado, para que el pad del rival tenga tiempo de
// llegar antes de hacer falta. Sin él, cualquier latencia congelaba el
// partido y al reanudarse corría hasta 12 pasos de golpe: el balón saltaba.
const INPUT_DELAY = 8;
// Límites del retraso de entrada adaptativo (pasos a 120 Hz): 8 = 67 ms,
// 30 = 250 ms. Más de eso ya no es jugable y mejor congelar un instante.
const MAX_INPUT_DELAY = 30;
const STEP_MS = STEP * 1000;

export function createOnlineMatch(seed: number, chars: MatchCharacters): Match {
  return createMatch({ mode: "online", difficulty: "normal", seed, characters: chars });
}

/**
 * Sesión lockstep. Dos conceptos separados:
 * - `side` ("host"|"guest") = autoridad de resync: el anfitrión de la sala
 *   es la referencia (manda las fotos); los demás se detectan solos con sus
 *   hashes y piden el estado. No tiene nada que ver con el lado del partido.
 * - `mySide` ("p0"|"p1"|null) = qué pad controlo yo. null = espectador: no
 *   mando pads, sigo el partido con los pads etiquetados que reenvía el
 *   anfitrión (ver `receiveSidePad`). Por defecto se deriva de `side`
 *   (anfitrión p0, invitado p1), como en el 1v1 original.
 */
export class OnlineSession {
  readonly side: "host" | "guest";
  readonly mySide: MatchSide;
  match: Match;
  step = 0;
  sendStep = 0;
  onHash: ((step: number, hash: string) => void) | null = null;
  onDesync: ((step: number) => void) | null = null;
  /** Últimos hashes de sincronía, para la prueba de dos navegadores. */
  hashLog: { step: number; hash: string }[] = [];
  /** Se llama justo antes de cada paso (la interpolación guarda ahí el estado previo). */
  beforeStep: (() => void) | null = null;
  /** Retraso de entrada vigente (pasos). Sube de a 1 hacia `targetDelay`. */
  inputDelay = INPUT_DELAY;
  private targetDelay = INPUT_DELAY;
  /** Mínimo que impone la red (mitad del RTT + margen). El ping NO lo sube más. */
  private floorDelay = INPUT_DELAY;
  /** Frames seguidos sin quedarse esperando al rival. */
  private calmFrames = 0;
  /** true mientras falta el pad del rival para un paso que ya tocaba simular. */
  private waiting = false;

  private myPads = new Map<number, InputPad>();
  private remotePads = new Map<number, InputPad>();
  private myHashes = new Map<number, string>();
  private remoteHashes = new Map<number, string>();
  private lastHashStep = -HASH_EVERY;
  private resyncing = false;

  // OJO: el lado por defecto va como parámetro por defecto, no con `??`:
  // `null` (espectador) es un valor válido y `??` lo convertiría en p1.
  constructor(
    match: Match,
    side: "host" | "guest",
    mySide: "p0" | "p1" | null = side === "host" ? "p0" : "p1",
  ) {
    this.match = match;
    this.side = side;
    this.mySide = mySide;
  }

  /** Guarda el paquete remoto, expandido a un pad por paso. */
  receivePad(from: number, n: number, pad: InputPad): void {
    for (let i = 0; i < n; i++) {
      this.remotePads.set(from + i, i === 0 ? pad : stripEdges(pad));
    }
    this.prune();
  }

  /**
   * Pads guardados desde un paso (por lado), para acompañar a una foto: el
   * par que restaura ha perdido los pads que tenía en vuelo y sin ellos se
   * quedaría congelado en el paso de la foto (los pads ya enviados no se
   * reenvían solos). Cada paso lleva los lados que ya están aquí; el lado
   * que falta llega en vivo después. Los bordes ya vienen aplicados por
   * paso, así que se reenvían de uno en uno (n=1).
   */
  bufferedPads(fromStep: number): Array<{ step: number; p0?: InputPad; p1?: InputPad }> {
    const out: Array<{ step: number; p0?: InputPad; p1?: InputPad }> = [];
    for (let s = fromStep; s < this.sendStep; s++) {
      const mine = this.myPads.get(s);
      const remote = this.remotePads.get(s);
      if (!mine && !remote) continue;
      out.push(
        this.mySide === "p1"
          ? { step: s, p0: remote, p1: mine }
          : { step: s, p0: mine, p1: remote },
      );
    }
    return out;
  }

  /**
   * Guarda un paquete etiquetado por lado (solo espectadores, incluido el
   * anfitrión cuando especta): el pad de p0 va a `myPads` y el de p1 a
   * `remotePads`, con la misma convención de bordes que `sendFrame` +
   * `receivePad` (pad completo en el primer paso, sin bordes en el resto).
   * Así el espectador reutiliza el lockstep entero (puerta de retraso,
   * hash, resync) sin duplicar ni una línea: `sendStep` avanza con el
   * paquete más adelantado de los dos lados y `runSteps` simula cuando
   * tiene los dos pads de cada paso.
   */
  receiveSidePad(side: "p0" | "p1", from: number, n: number, pad: InputPad): void {
    const map = side === "p0" ? this.myPads : this.remotePads;
    for (let i = 0; i < n; i++) {
      map.set(from + i, i === 0 ? pad : stripEdges(pad));
    }
    this.sendStep = Math.max(this.sendStep, from + n);
    this.prune();
  }

  /**
   * Envía mi pad de este frame y lo guarda para mis pasos. `n` viene del
   * acumulador del bucle (1-8). Devuelve el paquete enviado o null si hay
   * que frenar porque el partido va muy por detrás.
   */
  sendFrame(pad: InputPad, n: number): { from: number; n: number; pad: InputPad } | null {
    if (n <= 0) return null;
    if (this.sendStep - this.step >= MAX_GAP) return null;
    const pkt = { from: this.sendStep, n, pad };
    for (let i = 0; i < n; i++) {
      this.myPads.set(this.sendStep + i, i === 0 ? pad : stripEdges(pad));
    }
    this.sendStep += n;
    this.prune();
    return pkt;
  }

  /**
   * Fija el MÍNIMO del retraso de entrada con la latencia medida (mitad del
   * RTT más un margen). El jitter solo se usa para el valor inicial: el
   * ping de 0,5 s es demasiado burdo para seguir los picos y con 4G
   * sobreestimaba (ping de 49 ms con retraso de 183 ms, input pesado).
   * Lo demás lo decide la espera real, ver `adaptToStalls`.
   * Es solo local: los pads van indexados por paso, no afecta la sincronía.
   */
  setLatency(rttMs: number, jitterMs: number, immediate = false): void {
    const floor = Math.ceil((rttMs / 2 + 8) / STEP_MS);
    this.floorDelay = Math.max(INPUT_DELAY, Math.min(MAX_INPUT_DELAY, floor));
    if (immediate && this.step === 0) {
      // Antes del primer paso no hay nada que congelar: empezar ya con un
      // colchón para el jitter medido en la sala.
      const start = this.floorDelay + Math.ceil((jitterMs * 0.5) / STEP_MS);
      this.targetDelay = Math.max(this.floorDelay, Math.min(MAX_INPUT_DELAY, start));
      this.inputDelay = this.targetDelay;
    } else {
      this.targetDelay = Math.max(this.targetDelay, this.floorDelay);
    }
  }

  /**
   * Ajuste por espera real (como AIMD de TCP): cuando el pad del rival
   * llegó tarde L pasos, se sube el retraso esos L pasos; tras varios
   * segundos sin esperas se baja de a 1 paso, hasta el mínimo de la red.
   * Mide justo lo que importa (¿se congeló el juego?) y no un ping aparte.
   */
  private adaptToStalls(lateSteps: number, stalledNow: boolean): void {
    if (stalledNow) {
      this.calmFrames = 0;
      return;
    }
    if (lateSteps >= 2) {
      const bump = Math.min(10, lateSteps);
      this.targetDelay = Math.min(MAX_INPUT_DELAY, Math.max(this.targetDelay, this.inputDelay + bump));
      this.calmFrames = 0;
      return;
    }
    // Calma: cada 2 s sin esperas, un paso menos (bajar no congela nada,
    // la simulación solo corre 1 paso extra de recuperación).
    if (++this.calmFrames >= 120 && this.targetDelay > this.floorDelay) {
      this.targetDelay--;
      this.calmFrames = 0;
    }
  }

  /** Pasos de simulación que aún le faltan por ejecutar a este lado. */
  get backlog(): number {
    return Math.max(0, this.sendStep - this.step - this.inputDelay);
  }

  /**
   * Ejecuta pasos mientras tenga los dos pads. El partido solo avanza así.
   * `maxSteps` limita los pasos por frame: el bucle pasa los del frame más
   * unos pocos de recuperación, para que tras un congelón la simulación
   * alcance al reloj de forma gradual y no de un salto.
   */
  runSteps(maxSteps: number = MAX_STEPS_PER_FRAME): void {
    const m = this.match;
    // Subir el retraso de a un paso por frame; bajarlo es inmediato (no
    // congela, solo hace correr un paso extra).
    const backlogBefore = this.backlog;
    if (this.inputDelay < this.targetDelay) this.inputDelay++;
    else if (this.inputDelay > this.targetDelay) this.inputDelay--;
    const limit = Math.min(MAX_STEPS_PER_FRAME, Math.max(1, maxSteps));
    let ran = 0;
    let ticks = 0;
    let stalledNow = false;
    while (ran < limit) {
      if (m.hitstop > 0) {
        if (ticks >= 8) break;
        m.hitstop -= STEP;
        ticks++;
        continue;
      }
      // Retraso de entrada: no simular un paso hasta haber enviado varios
      // por delante, para que el pad del rival ya esté aquí cuando toque.
      if (this.sendStep - this.step <= this.inputDelay) break;
      const mine = this.myPads.get(this.step);
      const remote = this.remotePads.get(this.step);
      if (!mine || !remote) {
        stalledNow = true;
        break; // esperando al rival: congelar, no adivinar
      }
      // Espectador (mySide null): myPads lleva a p0 y remotePads a p1, así
      // que se mapea como p0.
      const pads = this.mySide === "p1" ? { p0: remote, p1: mine } : { p0: mine, p1: remote };
      this.beforeStep?.();
      const froze = stepMatch(m, pads, STEP);
      this.myPads.delete(this.step);
      this.remotePads.delete(this.step);
      this.step++;
      ran++;
      this.maybeHash();
      if (froze) break; // igual que el bucle local: parar aquí este frame
    }
    this.lastRan = ran;
    if (stalledNow) this.waiting = true;
    // Al reanudarse tras una espera, el atraso acumulado (menos los pasos
    // normales de este frame) es lo tarde que llegó el pad del rival.
    const late = this.waiting && ran > 0 ? Math.max(0, backlogBefore - 3) : 0;
    if (ran > 0) this.waiting = false;
    this.adaptToStalls(late, stalledNow);
  }

  /** Pasos reales simulados en la última llamada a `runSteps`. */
  lastRan = 0;

  private maybeHash(): void {
    if (this.step > 0 && this.step % HASH_EVERY === 0 && this.step !== this.lastHashStep) {
      this.lastHashStep = this.step;
      const hash = stateHash(this.match);
      this.myHashes.set(this.step, hash);
      this.hashLog.push({ step: this.step, hash });
      if (this.hashLog.length > 3) this.hashLog.shift();
      this.onHash?.(this.step, hash);
      this.checkHash(this.step);
    }
  }

  /** Un hash remoto: comparar con el mío del mismo paso, cuando lo tenga. */
  receiveHash(step: number, hash: string): void {
    this.remoteHashes.set(step, hash);
    this.checkHash(step);
  }

  private checkHash(step: number): void {
    if (this.resyncing) return;
    const mine = this.myHashes.get(step);
    const remote = this.remoteHashes.get(step);
    if (mine === undefined || remote === undefined) return;
    if (mine !== remote) {
      this.resyncing = true;
      this.onDesync?.(step);
    }
    this.myHashes.delete(step);
    this.remoteHashes.delete(step);
  }

  /** Foto del estado actual para el resync (la manda el anfitrión). */
  snapshot(): { step: number; state: MatchState } {
    return { step: this.step, state: snapshotMatch(this.match) };
  }

  /**
   * Adoptar la foto del anfitrión y seguir desde su paso. Los pads
   * guardados se tiran y `sendStep` VUELVE al paso de la foto: el par
   * vuelve a muestrear desde ahí (un jugador) o recibe los pads
   * reenviados por el anfitrión (un espectador). Sin esto, el par se
   * quedaba congelado: su `sendStep` seguía por delante pero sus pads
   * para esos pasos ya no existían y nadie los reenviaba.
   */
  restore(snap: { step: number; state: MatchState }): void {
    restoreMatch(this.match, snap.state);
    this.step = snap.step;
    this.sendStep = snap.step;
    this.myPads.clear();
    this.remotePads.clear();
    this.myHashes.clear();
    this.remoteHashes.clear();
    // El registro de hashes también es de la partida vieja: si no se limpia,
    // un hash corrupto anterior a la foto seguiría comparándose después.
    this.hashLog.length = 0;
    this.lastHashStep = snap.step - (snap.step % HASH_EVERY);
    this.resyncing = false;
  }

  /** ¿Pido la foto? Solo el invitado la pide; el anfitrión la manda solo. */
  get needsState(): boolean {
    return this.resyncing && this.side === "guest";
  }

  clearResync(): void {
    this.resyncing = false;
  }

  private prune(): void {
    const floor = this.step - 2;
    // Borrar durante la iteración de un Map es seguro; evita copiar las
    // claves a un array nuevo en cada paquete (60 veces por segundo).
    for (const k of this.myPads.keys()) if (k < floor) this.myPads.delete(k);
    for (const k of this.remotePads.keys()) if (k < floor) this.remotePads.delete(k);
  }
}
