import { useEffect, useRef, useState, type ReactNode } from "react";
import { ChevronLeft, ChevronRight, CircleHelp, Pause, Play, Trophy, Users, Volume2, VolumeX, X } from "lucide-react";
import { blankPad, createMatch, stepMatch, stripEdges, type Difficulty, type InputPad, type Match, type MatchCharacters, type Mode, type Pads } from "@/game/engine";
import { STEP } from "@/game/constants";
import {
  createOnlineMatch,
  isRoomCode,
  makeRoomCode,
  nextRotation,
  OnlineNet,
  OnlineSession,
  queueAdd,
  queueRemove,
  roomCodeFromSearch,
  roomInviteLink,
  shortPeerId,
  stateHash,
  type NetMsg,
  type PeerRole,
  type QueueEntry,
} from "@/lib/multiplayer/online";
import { randomSeed } from "@/game/rng";
import { RenderInterp } from "@/game/interp";
import { migrateStorageKeys, STORAGE_KEYS } from "@/lib/storage-keys";
import { drawCharacterPreview, drawMatch, invalidateStaticLayer, type PreviewAction } from "@/game/draw";
import {
  CHARACTERS,
  getCharacter,
  isCharacterId,
  randomCharacterId,
  type CharacterId,
} from "@/game/characters";
import { crowdDanger, installAudioGestureUnlock, isMuted, playSfx, resumeAudio, setCrowdLevel, toggleMute, unlockAudio } from "@/game/audio";

type Screen = "menu" | "help" | "roster" | "match" | "online";
type FighterSlot = "left" | "right";
type Hud = {
  scoreL: number;
  scoreR: number;
  time: number;
  phase: Match["phase"];
  sudden: boolean;
  banner: string;
  mode: Mode;
  leftName: string;
  rightName: string;
};
type Selection = { left: CharacterId; right: CharacterId };
type Save = { wins: number; played: number; goals: number; best: number };
type HoldKey = "left" | "right" | "jump" | "attack" | "down";
type TouchSide = Record<HoldKey, boolean> & { leftAt: number; rightAt: number; jumpTaps: number };

const SAVE_KEY = STORAGE_KEYS.save;
const SELECTION_KEY = STORAGE_KEYS.selection;
const DEFAULT_SELECTION: Selection = { left: "tizo", right: "lumi" };

// Sala del anfitrión: sobrevive a que el navegador recargue la pestaña
// cuando se va a segundo plano (al compartir por WhatsApp). 15 minutos.
const HOST_ROOM_KEY = STORAGE_KEYS.hostRoom;
const HOST_ROOM_TTL_MS = 15 * 60 * 1000;

function saveHostRoom(code: string) {
  try {
    localStorage.setItem(HOST_ROOM_KEY, JSON.stringify({ code, at: Date.now() }));
  } catch {
    /* sin almacenamiento, la sala no sobrevive al recargo */
  }
}

function loadHostRoom(): string | null {
  migrateStorageKeys();
  try {
    const raw = localStorage.getItem(HOST_ROOM_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw) as { code?: unknown; at?: unknown };
    if (typeof parsed.code !== "string" || !isRoomCode(parsed.code)) return null;
    if (typeof parsed.at !== "number" || Date.now() - parsed.at > HOST_ROOM_TTL_MS) return null;
    return parsed.code;
  } catch {
    return null;
  }
}

function clearHostRoom() {
  try {
    localStorage.removeItem(HOST_ROOM_KEY);
  } catch {
    /* ignore */
  }
}

function loadSelection(): Selection {
  migrateStorageKeys();
  try {
    const raw = localStorage.getItem(SELECTION_KEY);
    if (!raw) return DEFAULT_SELECTION;
    const parsed = JSON.parse(raw) as Partial<Selection>;
    const left = isCharacterId(parsed.left) ? parsed.left : DEFAULT_SELECTION.left;
    const right = isCharacterId(parsed.right) ? parsed.right : DEFAULT_SELECTION.right;
    return left === right
      ? { left, right: CHARACTERS.find((c) => c.id !== left)?.id ?? DEFAULT_SELECTION.right }
      : { left, right };
  } catch {
    return DEFAULT_SELECTION;
  }
}

function emptyTouch(): TouchSide {
  return { left: false, right: false, jump: false, attack: false, down: false, leftAt: 0, rightAt: 0, jumpTaps: 0 };
}

function loadSave(): Save {
  migrateStorageKeys();
  try {
    const raw = localStorage.getItem(SAVE_KEY);
    if (!raw) return { wins: 0, played: 0, goals: 0, best: 0 };
    const p = JSON.parse(raw) as Partial<Save>;
    return {
      wins: Number(p.wins) || 0,
      played: Number(p.played) || 0,
      goals: Number(p.goals) || 0,
      best: Number(p.best) || 0,
    };
  } catch {
    return { wins: 0, played: 0, goals: 0, best: 0 };
  }
}

function fmt(total: number) {
  const t = Math.max(0, total);
  const m = Math.floor(t / 60);
  const s = t % 60;
  return `${m}:${s.toString().padStart(2, "0")}`;
}

function heldAxis(left: boolean, right: boolean, leftAt: number, rightAt: number) {
  if (left && right) return leftAt >= rightAt ? -1 : 1;
  if (left) return -1;
  if (right) return 1;
  return 0;
}

export function GoalFightersGame() {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const matchRef = useRef<Match | null>(null);
  const keysRef = useRef(new Set<string>());
  const keyAt = useRef<Record<string, number>>({});
  const touchRef = useRef({ p0: emptyTouch(), p1: emptyTouch() });
  const wasRef = useRef({ j0: false, a0: false, d0: false, j1: false, a1: false, d1: false });
  const screenRef = useRef<Screen>("menu");
  const pausedRef = useRef(false);
  const savedRef = useRef(false);
  const reduceRef = useRef(false);
  const hudSnap = useRef<Hud | null>(null);

  const [screen, setScreen] = useState<Screen>("menu");
  // Splash inicial: "toca para empezar" (además desbloquea el audio del móvil).
  const [splash, setSplash] = useState(true);
  const [paused, setPaused] = useState(false);
  const [muted, setMutedUi] = useState(false);
  const [mode, setMode] = useState<Mode>("cpu");
  const [difficulty, setDifficulty] = useState<Difficulty>("normal");
  const [stats, setStats] = useState<Save>({ wins: 0, played: 0, goals: 0, best: 0 });
  const [hud, setHud] = useState<Hud | null>(null);
  // El medidor de FPS se escribe directo al DOM: como estado re-renderizaba
  // todo el componente 2 veces por segundo en pleno partido.
  const fpsElRef = useRef<HTMLSpanElement>(null);
  const [live, setLive] = useState("");
  const [selection, setSelection] = useState<Selection>(DEFAULT_SELECTION);
  const [activeSlot, setActiveSlot] = useState<FighterSlot>("left");
  const [rosterNotice, setRosterNotice] = useState("");

  // Online 1 vs 1 (lockstep por PeerJS; ver src/lib/multiplayer/online.ts).
  const netRef = useRef<OnlineNet | null>(null);
  const sessionRef = useRef<OnlineSession | null>(null);
  const onlineSideRef = useRef<"host" | "guest" | null>(null);
  const rosterFromRef = useRef<Screen>("menu");
  const lastSyncRef = useRef("");
  const interpRef = useRef(new RenderInterp());
  const arenaRef = useRef<HTMLDivElement>(null);
  const [onlineView, setOnlineView] = useState<"idle" | "waiting" | "joining" | "connected" | "spectating" | "error">("idle");
  const [roomCode, setRoomCode] = useState("");
  const [joinCode, setJoinCode] = useState("");
  const [onlineError, setOnlineError] = useState("");
  const [onlineRtt, setOnlineRtt] = useState<number | null>(null);
  const [shareNote, setShareNote] = useState("");
  const roomCodeRef = useRef("");
  const joinRetriesRef = useRef(0);
  const joinRetryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const [rivalChar, setRivalChar] = useState<CharacterId | null>(null);
  const [rematchWaiting, setRematchWaiting] = useState(false);
  const [menuNotice, setMenuNotice] = useState("");

  // Espectadores y cola de turnos (ver src/lib/multiplayer/online.ts).
  // El rol (jugador/espectador) lo asigna el anfitrión; el lado del partido
  // (p0/p1) viene en cada mensaje `start` y puede cambiar al rotar.
  const [onlineRole, setOnlineRole] = useState<PeerRole | null>(null);
  const onlineRoleRef = useRef<PeerRole | null>(null);
  const [queue, setQueue] = useState<QueueEntry[]>([]);
  const queueRef = useRef<QueueEntry[]>([]);
  const [spectatorChar, setSpectatorChar] = useState<CharacterId>("tizo");
  const [loserOverlay, setLoserOverlay] = useState(false);
  const [roomNotice, setRoomNotice] = useState("");
  const [, setPeersTick] = useState(0);
  /** Anfitrión: quién ocupa cada lado ("me" = yo, null = libre). */
  const sidesRef = useRef<{ p0: string | "me" | null; p1: string | "me" | null }>({ p0: null, p1: null });
  /** Anfitrión: luchador de cada par (por hello o por petición de turno). */
  const peerCharsRef = useRef(new Map<string, CharacterId>());
  /** Partido en curso (semilla y luchadores), para el espectador que entra a mitad. */
  const currentMatchRef = useRef<{ seed: number; left: CharacterId; right: CharacterId } | null>(null);
  /** La rotación de este partido ya se disparó (una sola vez por partido). */
  const rotatedRef = useRef(false);
  /** Pares conocidos (para detectar en onPeersChanged quién entró o salió). */
  const knownPeersRef = useRef(new Set<string>());

  function setRoleBoth(role: PeerRole | null) {
    onlineRoleRef.current = role;
    setOnlineRole(role);
  }

  function setQueueBoth(next: QueueEntry[]) {
    queueRef.current = next;
    setQueue(next);
  }

  const modeRef = useRef(mode);
  const diffRef = useRef(difficulty);
  const selectionRef = useRef(selection);
  modeRef.current = mode;
  diffRef.current = difficulty;
  selectionRef.current = selection;

  function go(next: Screen) {
    screenRef.current = next;
    setScreen(next);
  }

  function setHold(side: "p0" | "p1", key: HoldKey, down: boolean) {
    const t = touchRef.current[side];
    t[key] = down;
    if (down && key === "left") t.leftAt = performance.now();
    if (down && key === "right") t.rightAt = performance.now();
    if (down && key === "jump") t.jumpTaps++;
  }

  function startMatch() {
    if (modeRef.current === "online") {
      go("online");
      return;
    }
    unlockAudio();
    playSfx("ui", 0, 0.8);
    setMenuNotice("");
    savedRef.current = false;
    pausedRef.current = false;
    hudSnap.current = null;
    setPaused(false);
    matchRef.current = createMatch({
      mode: modeRef.current,
      difficulty: diffRef.current,
      characters: selectionRef.current,
    });
    interpRef.current.reset();
    // Test-only capture hook: start with the ball flying into the right net
    // so the goal effect can be recorded, with the shooter near the goal so
    // the camera frames the net up close. Compile-time flag; production
    // builds never set it, so this code is dead there.
    if (import.meta.env.VITE_DEMO_GOAL === "1") {
      const dm = matchRef.current;
      dm.ball.x = 900;
      dm.ball.y = 330;
      dm.ball.vx = 850;
      dm.ball.vy = 0;
      const shooter = dm.fighters[0];
      shooter.x = 700;
      shooter.y = 486;
      shooter.vx = 0;
      shooter.vy = 0;
    }
    go("match");
  }

  /* ---------------- Online 1 vs 1 ---------------- */

  function myOnlineChar(): CharacterId {
    const side = onlineSideRef.current ?? "host";
    return side === "host" ? selectionRef.current.left : selectionRef.current.right;
  }

  function wireNet(net: OnlineNet, side: "host" | "guest") {
    net.onRtt = (ms) => setOnlineRtt(ms);
    // Retraso de entrada según la red real (RTT + jitter), no un valor fijo.
    // Solo vale la latencia de un jugador (el rival, o el anfitrión si yo
    // soy el invitado): la de un espectador no mueve mi partido.
    net.onLatency = (rtt, jitter, from) => {
      if (side === "host" && net.peerRole(from) !== "player") return;
      sessionRef.current?.setLatency(rtt, jitter);
    };
    // Un par entró o salió: el anfitrión reacciona (el invitado solo repinta).
    net.onPeersChanged = () => {
      if (netRef.current !== net) return;
      setPeersTick((t) => t + 1);
      if (side !== "host") return;
      const now = new Set(net.peersList().map((p) => p.id));
      for (const id of now) {
        if (knownPeersRef.current.has(id)) continue;
        knownPeersRef.current.add(id);
        // Recién conectado y espectador: cola + partido en curso (si hay).
        if (net.peerRole(id) === "spectator") {
          net.sendTo(id, { t: "queue", entries: queueRef.current });
          sendMatchStateTo(id);
        }
      }
      for (const id of [...knownPeersRef.current]) {
        if (now.has(id)) continue;
        knownPeersRef.current.delete(id);
        // Salió: si jugaba, es abandono (forfeitPlayer no hace nada si no
        // jugaba); si esperaba turno, sale de la cola.
        forfeitPlayer(id);
        if (queueRef.current.some((e) => e.id === id)) {
          setQueueBoth(queueRemove(queueRef.current, id));
          broadcastQueue();
        }
      }
    };
    net.onStatus = (s, detail) => {
      // Un evento de una conexión ya reemplazada o cancelada no debe tocar la UI.
      if (netRef.current !== net) return;
      if (s === "waiting") setOnlineView("waiting");
      else if (s === "connected") {
        joinRetriesRef.current = 0;
        setOnlineView("connected");
        // El hello ya no va aquí: el invitado espera a que el anfitrión le
        // asigne su rol (`role`) y solo saluda si le toca jugar.
      } else if (s === "closed") {
        // El anfitrión gestiona las salidas en onPeersChanged (abandono,
        // cola); aquí solo el invitado, a quien se le cayó el anfitrión.
        if (side === "host") return;
        if (screenRef.current === "match" && matchRef.current?.mode === "online") {
          leaveOnline("Se perdió la conexión con la sala.");
        } else {
          setOnlineView("idle");
          setOnlineError("Se cerró la conexión. Prueba de nuevo.");
        }
      } else if (s === "error") {
        if (detail === "taken") {
          createOnlineRoom();
        } else if (detail === "not-found") {
          // La sala puede estar re-registrándose (el anfitrión volvió de
          // WhatsApp): reintentar unos segundos antes de darla por perdida.
          if (joinRetriesRef.current < 5) {
            joinRetriesRef.current++;
            joinRetryTimerRef.current = setTimeout(() => {
              joinRetryTimerRef.current = null;
              if (roomCodeRef.current) joinOnlineRoom(roomCodeRef.current);
            }, 2000);
          } else {
            setOnlineView("idle");
            setOnlineError("No existe una sala con ese código. Revísalo y prueba de nuevo.");
          }
        } else if (side === "host" && document.visibilityState === "hidden") {
          // Fallos mientras la app está en segundo plano (compartiendo la sala):
          // son esperados. Al volver, la sala se vuelve a registrar sola.
        } else {
          setOnlineView("idle");
          setOnlineError("No se pudo conectar. Revisa tu internet y prueba de nuevo.");
        }
      }
    };
    net.onMessage = (msg: NetMsg, from: string) => {
      const session = sessionRef.current;
      if (msg.t === "role") {
        // El anfitrión me asignó mi rol en la sala.
        setRoleBoth(msg.role);
        if (msg.role === "player") {
          net.sendToHost({ t: "hello", name: "Rival", char: myOnlineChar() });
        } else {
          setOnlineView("spectating");
        }
      } else if (msg.t === "hello") {
        // Solo vale del jugador: los espectadores no saludan.
        if (side !== "host" || net.peerRole(from) !== "player") return;
        peerCharsRef.current.set(from, msg.char);
        if (onlineRoleRef.current === "player") setRivalChar(msg.char);
        // ¿Hay partido en curso? Entonces no hay hueco (los dos lados están
        // ocupados): el saludo llega tarde y el par baja a espectador.
        const active = session && session.match.phase !== "over";
        if (active) {
          demoteToSpectator(from);
          return;
        }
        // Sin partido: el que acaba de llegar juega contra el que espera
        // (yo, si juego, o el jugador que quedó solo tras un abandono).
        const sides = sidesRef.current;
        const free: "p0" | "p1" | null = sides.p0 === null ? "p0" : sides.p1 === null ? "p1" : null;
        if (!free) {
          demoteToSpectator(from);
          return;
        }
        const other = free === "p0" ? "p1" : "p0";
        const otherHolder = sides[other];
        if (otherHolder === null) {
          // Nadie espera: el recién llegado ocupa el lado libre y espera
          // a que entre otro (el anfitrión especta).
          sides[free] = from;
          setRoomNotice("Esperando a otro jugador…");
          return;
        }
        const otherChar =
          otherHolder === "me" ? selectionRef.current.left : (peerCharsRef.current.get(otherHolder) ?? "tizo");
        const p0 =
          free === "p0"
            ? { holder: from as string | "me", char: msg.char }
            : { holder: otherHolder, char: otherChar };
        const p1 =
          free === "p1"
            ? { holder: from as string | "me", char: msg.char }
            : { holder: otherHolder, char: otherChar };
        hostStartMatch(p0, p1);
      } else if (msg.t === "start") {
        // `you` es mi lado en este partido (o espectador, si perdí y bajé).
        setRivalChar(msg.you === "p0" ? msg.right : msg.you === "p1" ? msg.left : null);
        startOnlineMatch(msg.seed, { left: msg.left, right: msg.right }, msg.you);
      } else if (msg.t === "pad") {
        if (side === "host") {
          // Un jugador me manda su pad: alimentar mi sesión y reenviar.
          const senderSide = sideOfPeer(from);
          if (!senderSide) return; // un espectador no manda pads
          if (session) {
            if (session.mySide !== null) session.receivePad(msg.from, msg.n, msg.pad);
            else session.receiveSidePad(senderSide, msg.from, msg.n, msg.pad);
          }
          // Al otro jugador, sin etiqueta (para él es "el pad del rival").
          const other = otherPlayerPeer(from);
          if (other) net.sendTo(other, { t: "pad", from: msg.from, n: msg.n, pad: msg.pad });
          // A los espectadores, etiquetado con el lado.
          net.sendToSpectators({ t: "pad", from: msg.from, n: msg.n, pad: msg.pad, side: senderSide });
        } else if (session) {
          if (session.mySide === null) {
            // Espectador: solo valen los pads etiquetados por lado.
            if (msg.side) session.receiveSidePad(msg.side, msg.from, msg.n, msg.pad);
          } else {
            session.receivePad(msg.from, msg.n, msg.pad);
          }
        }
      } else if (msg.t === "hash") {
        // Solo el anfitrión difunde hashes; cada par se compara solo.
        if (side === "host") return;
        session?.receiveHash(msg.step, msg.hash);
      } else if (msg.t === "snapshot") {
        if (side === "host") return;
        session?.restore(msg);
        interpRef.current.reset();
      } else if (msg.t === "needstate") {
        if (session && side === "host") {
          sendSnapshotTo(from);
          session.clearResync();
        }
      } else if (msg.t === "rematch") {
        // Solo vale de un jugador en cancha.
        if (side === "host" && net.peerRole(from) === "player") requestRematch();
      } else if (msg.t === "request-turn") {
        if (side !== "host" || net.peerRole(from) !== "spectator") return;
        // El luchador no puede ser uno de los que está en cancha.
        const inPlay = session
          ? [session.match.fighters[0].character, session.match.fighters[1].character]
          : [];
        if (inPlay.includes(msg.char)) return;
        peerCharsRef.current.set(from, msg.char);
        const next = queueAdd(queueRef.current, { id: from, char: msg.char });
        if (next !== queueRef.current) {
          setQueueBoth(next);
          broadcastQueue();
        }
      } else if (msg.t === "cancel-turn") {
        if (side !== "host") return;
        const next = queueRemove(queueRef.current, from);
        if (next.length !== queueRef.current.length) {
          setQueueBoth(next);
          broadcastQueue();
        }
      } else if (msg.t === "queue") {
        if (side === "host") return;
        setQueueBoth(msg.entries);
      } else if (msg.t === "match-end") {
        // Un jugador abandonó y no había cola: el partido terminó para
        // todos. Volver a la sala SIN desconectar.
        sessionRef.current = null;
        currentMatchRef.current = null;
        setRoomNotice("Un jugador salió y el partido terminó.");
        setOnlineView(onlineRoleRef.current === "spectator" ? "spectating" : "waiting");
        go("online");
      } else if (msg.t === "bye") {
        if (side === "host") {
          forfeitPlayer(from);
          const next = queueRemove(queueRef.current, from);
          if (next.length !== queueRef.current.length) {
            setQueueBoth(next);
            broadcastQueue();
          }
        } else {
          leaveOnline("El anfitrión cerró la sala.");
        }
      }
    };
  }

  /** Anfitrión: lado que ocupa un par ("p0"|"p1"), o null si no juega. */
  function sideOfPeer(peerId: string): "p0" | "p1" | null {
    const sides = sidesRef.current;
    if (sides.p0 === peerId) return "p0";
    if (sides.p1 === peerId) return "p1";
    return null;
  }

  /** Anfitrión: el OTRO jugador remoto (para reenviarle pads), o null si soy yo. */
  function otherPlayerPeer(peerId: string): string | null {
    const sides = sidesRef.current;
    const other = sides.p0 === peerId ? sides.p1 : sides.p1 === peerId ? sides.p0 : null;
    return other !== null && other !== "me" ? other : null;
  }

  /** Anfitrión: difundir la cola a todos los pares. */
  function broadcastQueue(): void {
    netRef.current?.broadcast({ t: "queue", entries: queueRef.current });
  }

  /** Anfitrión: mandar a un espectador el partido en curso (start + foto). */
  function sendMatchStateTo(peerId: string): void {
    const net = netRef.current;
    const session = sessionRef.current;
    const info = currentMatchRef.current;
    if (!net || !session || !info || session.match.phase === "over") return;
    net.sendTo(peerId, { t: "start", seed: info.seed, left: info.left, right: info.right, you: "spectator" });
    sendSnapshotTo(peerId);
  }

  /**
   * Anfitrión: mandar la foto del partido a un par, con los pads en vuelo
   * que ya tengo (sin ellos el par se congela en el paso de la foto). Al
   * espectador le van los dos lados (etiquetados); al jugador, solo los
   * del OTRO lado (los suyos los vuelve a muestrear desde la foto).
   */
  function sendSnapshotTo(peerId: string): void {
    const net = netRef.current;
    const session = sessionRef.current;
    if (!net || !session) return;
    const snap = session.snapshot();
    net.sendTo(peerId, { t: "snapshot", ...snap });
    const toSpectator = net.peerRole(peerId) === "spectator";
    for (const { step, p0, p1 } of session.bufferedPads(snap.step)) {
      if (toSpectator) {
        if (p0) net.sendTo(peerId, { t: "pad", from: step, n: 1, pad: p0, side: "p0" });
        if (p1) net.sendTo(peerId, { t: "pad", from: step, n: 1, pad: p1, side: "p1" });
      } else {
        const reqSide = sideOfPeer(peerId);
        const other = reqSide === "p0" ? p1 : reqSide === "p1" ? p0 : undefined;
        if (other) net.sendTo(peerId, { t: "pad", from: step, n: 1, pad: other });
      }
    }
  }

  /** Anfitrión: bajar a un par a espectador (llegó tarde, sin hueco). */
  function demoteToSpectator(peerId: string): void {
    const net = netRef.current;
    if (!net) return;
    net.setRole(peerId, "spectator");
    net.sendTo(peerId, { t: "role", role: "spectator" });
    net.sendTo(peerId, { t: "queue", entries: queueRef.current });
    sendMatchStateTo(peerId);
  }

  async function createOnlineRoom(codeArg?: string) {
    const code = codeArg ?? makeRoomCode();
    setRoomCode(code);
    roomCodeRef.current = code;
    setJoinCode("");
    setOnlineError("");
    setRivalChar(null);
    setOnlineRtt(null);
    setShareNote("");
    setRoomNotice("");
    setQueueBoth([]);
    setRoleBoth("player");
    setLoserOverlay(false);
    rotatedRef.current = false;
    currentMatchRef.current = null;
    // El creador juega de entrada (lado izquierdo); el rival toma el otro.
    sidesRef.current = { p0: "me", p1: null };
    peerCharsRef.current.clear();
    knownPeersRef.current.clear();
    setOnlineView("waiting");
    saveHostRoom(code);
    netRef.current?.close();
    const net = new OnlineNet();
    net.maxRemotePlayers = 1;
    netRef.current = net;
    onlineSideRef.current = "host";
    wireNet(net, "host");
    await net.createRoom(code);
  }

  async function joinOnlineRoom(codeArg?: string) {
    const code = (codeArg ?? joinCode).trim().toUpperCase();
    if (!isRoomCode(code)) {
      setOnlineError("El código tiene 4 letras. Revísalo y prueba de nuevo.");
      return;
    }
    if (code !== roomCodeRef.current) joinRetriesRef.current = 0;
    setRoomCode(code);
    roomCodeRef.current = code;
    setJoinCode(code);
    setOnlineError("");
    setRivalChar(null);
    setOnlineRtt(null);
    setRoomNotice("");
    setQueueBoth([]);
    setRoleBoth(null);
    setLoserOverlay(false);
    rotatedRef.current = false;
    currentMatchRef.current = null;
    setOnlineView("joining");
    netRef.current?.close();
    const net = new OnlineNet();
    netRef.current = net;
    onlineSideRef.current = "guest";
    wireNet(net, "guest");
    await net.joinRoom(code);
  }

  /** Salir de la sala online (botón Cancelar): corta también el reintento. */
  function cancelOnline() {
    if (joinRetryTimerRef.current) clearTimeout(joinRetryTimerRef.current);
    joinRetryTimerRef.current = null;
    joinRetriesRef.current = 0;
    netRef.current?.close();
    netRef.current = null;
    onlineSideRef.current = null;
    setRoleBoth(null);
    setQueueBoth([]);
    setLoserOverlay(false);
    setRoomNotice("");
    rotatedRef.current = false;
    currentMatchRef.current = null;
    // Cancelar no es un error: limpiar cualquier aviso pendiente y olvidar la
    // sala para que al volver a la app no se re-cree sola.
    setOnlineError("");
    clearHostRoom();
    setOnlineView("idle");
  }

  /** Compartir el enlace de la sala: hoja nativa en el celular, o copiar. */
  async function shareRoomLink() {
    if (!roomCode) return;
    const link = roomInviteLink(roomCode);
    setShareNote("");
    if (typeof navigator === "undefined") {
      setShareNote("Copia el enlace de abajo y pásalo a tu rival.");
      return;
    }
    const nav = navigator as Navigator & { share?: (data: ShareData) => Promise<void> };
    if (typeof nav.share === "function") {
      try {
        await nav.share({
          title: "Goal Fighters — sala online",
          text: `Únete a mi sala de Goal Fighters: ${link}`,
          url: link,
        });
        setShareNote("Enlace compartido.");
        return;
      } catch {
        return; // El usuario cerró el menú de compartir: no pasa nada.
      }
    }
    try {
      await navigator.clipboard.writeText(link);
      setShareNote("¡Enlace copiado! Pásalo a tu rival.");
    } catch {
      setShareNote("Copia el enlace de abajo y pásalo a tu rival.");
    }
  }

  function startOnlineMatch(seed: number, chars: MatchCharacters, you: "p0" | "p1" | "spectator") {
    const authority = onlineSideRef.current ?? "host";
    const mySide = you === "spectator" ? null : you;
    // Jugaba y ahora miro: perdí y bajé a espectador (la rotación me sacó).
    const wasPlayer = sessionRef.current?.mySide != null;
    resumeAudio();
    const match = createOnlineMatch(seed, chars);
    const session = new OnlineSession(match, authority, mySide);
    interpRef.current.reset();
    const lat = netRef.current?.latency;
    if (lat) session.setLatency(lat.rtt, lat.jitter, true);
    session.beforeStep = () => interpRef.current.capture(match);
    // Solo el anfitrión difunde hashes (a todos): cada par se compara solo
    // y pide la foto si diverge. El anfitrión no compara nada entrante.
    session.onHash =
      authority === "host"
        ? (step, hash) => netRef.current?.broadcast({ t: "hash", step, hash })
        : null;
    session.onDesync = () => {
      if (authority !== "host") netRef.current?.sendToHost({ t: "needstate" });
    };
    sessionRef.current = session;
    savedRef.current = false;
    pausedRef.current = false;
    setPaused(false);
    setRematchWaiting(false);
    setLoserOverlay(wasPlayer && you === "spectator");
    setRoleBoth(you === "spectator" ? "spectator" : "player");
    if (you === "spectator") {
      // Mi figura por defecto para pedir turno: la primera que no esté en cancha.
      const inPlay = [match.fighters[0].character, match.fighters[1].character];
      const first = CHARACTERS.find((c) => !inPlay.includes(c.id));
      if (first) setSpectatorChar(first.id);
    }
    // El anfitrión que especta admite DOS jugadores remotos; si juega, uno.
    if (authority === "host" && netRef.current) {
      netRef.current.maxRemotePlayers = you === "spectator" ? 2 : 1;
    }
    rotatedRef.current = false;
    // Los luchadores reales del partido (por si `chars` venía parcial).
    currentMatchRef.current = {
      seed,
      left: match.fighters[0].character,
      right: match.fighters[1].character,
    };
    matchRef.current = match;
    hudSnap.current = null;
    go("match");
  }

  /**
   * Anfitrión: arrancar un partido entre dos ocupantes (cada uno es "me" o
   * un peerId) con sus luchadores. Normaliza los roles de red (los dos
   * jugadores suben, el resto baja a espectador), manda a cada uno su
   * `start` personalizado y arranca la sesión propia.
   */
  function hostStartMatch(
    p0: { holder: string | "me"; char: CharacterId },
    p1: { holder: string | "me"; char: CharacterId },
  ): void {
    const net = netRef.current;
    if (!net || onlineSideRef.current !== "host") return;
    const seed = randomSeed();
    const chars = { left: p0.char, right: p1.char };
    sidesRef.current = { p0: p0.holder, p1: p1.holder };
    // Roles de red ANTES de mandar nada: el start de espectador debe
    // excluir a los dos jugadores (y el perdedor ya es espectador).
    for (const id of net.playerIds()) {
      if (id !== p0.holder && id !== p1.holder) net.setRole(id, "spectator");
    }
    for (const id of net.spectatorIds()) {
      if (id === p0.holder || id === p1.holder) net.setRole(id, "player");
    }
    if (p0.holder !== "me") net.sendTo(p0.holder, { t: "start", seed, ...chars, you: "p0" });
    if (p1.holder !== "me") net.sendTo(p1.holder, { t: "start", seed, ...chars, you: "p1" });
    net.sendToSpectators({ t: "start", seed, ...chars, you: "spectator" });
    const myYou = p0.holder === "me" ? "p0" : p1.holder === "me" ? "p1" : "spectator";
    startOnlineMatch(seed, chars, myYou);
  }

  /**
   * Anfitrión: al terminar el partido, si hay cola, la siguiente partida
   * arranca de una (retador contra ganador). Sin cola no hace nada: sale la
   * ventana actual y la revancha la piden los jugadores.
   */
  function maybeRotate(): boolean {
    const session = sessionRef.current;
    if (!session || onlineSideRef.current !== "host") return false;
    if (session.match.phase !== "over" || rotatedRef.current) return false;
    const rot = nextRotation(session.match.scoreL, session.match.scoreR, queueRef.current);
    if (!rot) return false;
    const sides = sidesRef.current;
    const winnerHolder = sides[rot.winnerSide];
    if (winnerHolder === null) {
      // El ganador salió en la ventana final: juegan los dos primeros de
      // la cola entre sí (si hay dos); si no, se espera (sin marcar la
      // rotación, para reintentarlo si la cola crece).
      const [first, second, ...rest] = queueRef.current;
      if (!first || !second) return false;
      rotatedRef.current = true;
      setQueueBoth(rest);
      broadcastQueue();
      hostStartMatch(
        { holder: first.id, char: first.char },
        { holder: second.id, char: second.char },
      );
      return true;
    }
    rotatedRef.current = true;
    setQueueBoth(rot.rest);
    broadcastQueue();
    const winnerChar =
      rot.winnerSide === "p0"
        ? session.match.fighters[0].character
        : session.match.fighters[1].character;
    const p0 =
      rot.winnerSide === "p0"
        ? { holder: winnerHolder, char: winnerChar }
        : { holder: rot.challenger.id as string | "me", char: rot.challenger.char };
    const p1 =
      rot.winnerSide === "p1"
        ? { holder: winnerHolder, char: winnerChar }
        : { holder: rot.challenger.id as string | "me", char: rot.challenger.char };
    hostStartMatch(p0, p1);
    return true;
  }

  /**
   * Anfitrión: un jugador se fue (bye o cierre). Si había partido en curso,
   * el que queda gana por abandono: con cola rota de una; sin cola avisa a
   * todos de que el partido terminó. Sin partido, solo libera el lado.
   * No hace nada si el par no jugaba (era espectador).
   */
  function forfeitPlayer(peerId: string): void {
    const net = netRef.current;
    if (!net || onlineSideRef.current !== "host") return;
    const sides = sidesRef.current;
    const side: "p0" | "p1" | null = sides.p0 === peerId ? "p0" : sides.p1 === peerId ? "p1" : null;
    if (!side) return;
    const otherSide = side === "p0" ? "p1" : "p0";
    const otherHolder = sides[otherSide];
    sides[side] = null;
    const session = sessionRef.current;
    if (!session || session.match.phase === "over") return;
    rotatedRef.current = true; // el partido viejo ya no rota
    if (queueRef.current.length > 0 && otherHolder !== null) {
      const [challenger, ...rest] = queueRef.current;
      setQueueBoth(rest);
      broadcastQueue();
      const winnerChar =
        otherSide === "p0"
          ? session.match.fighters[0].character
          : session.match.fighters[1].character;
      const p0 =
        otherSide === "p0"
          ? { holder: otherHolder, char: winnerChar }
          : { holder: challenger.id as string | "me", char: challenger.char };
      const p1 =
        otherSide === "p1"
          ? { holder: otherHolder, char: winnerChar }
          : { holder: challenger.id as string | "me", char: challenger.char };
      hostStartMatch(p0, p1);
    } else {
      net.broadcast({ t: "match-end", leaver: shortPeerId(peerId) });
      sessionRef.current = null;
      currentMatchRef.current = null;
      setRoomNotice("Un jugador salió y el partido terminó.");
      setOnlineView("waiting");
      go("online");
    }
  }

  function requestRematch() {
    const net = netRef.current;
    const session = sessionRef.current;
    if (!net || !session) return;
    if (session.side === "host") {
      // Con cola, la cola manda: rotar en vez de repetir pareja.
      if (queueRef.current.length > 0 && session.match.phase === "over") {
        if (maybeRotate()) return;
      }
      // Si ya empezó otro partido (rotación), no hay revancha.
      if (session.match.phase !== "over") return;
      const sides = sidesRef.current;
      if (sides.p0 === null || sides.p1 === null) return; // falta un jugador
      hostStartMatch(
        { holder: sides.p0, char: session.match.fighters[0].character },
        { holder: sides.p1, char: session.match.fighters[1].character },
      );
    } else {
      setRematchWaiting(true);
      net.sendToHost({ t: "rematch" });
    }
  }

  /** Espectador: pedir turno con el luchador elegido (no puede estar en cancha). */
  function requestTurn() {
    const net = netRef.current;
    if (!net || onlineRoleRef.current !== "spectator") return;
    const session = sessionRef.current;
    const inPlay = session
      ? [session.match.fighters[0].character, session.match.fighters[1].character]
      : [];
    const available = CHARACTERS.filter((c) => !inPlay.includes(c.id));
    const char = available.some((c) => c.id === spectatorChar)
      ? spectatorChar
      : (available[0]?.id ?? null);
    if (!char) return;
    setSpectatorChar(char);
    net.sendToHost({ t: "request-turn", char });
  }

  /** Espectador: cancelar mi turno en la cola. */
  function cancelTurn() {
    netRef.current?.sendToHost({ t: "cancel-turn" });
  }

  function leaveOnline(notice?: string) {
    const net = netRef.current;
    if (net?.connected) {
      // El anfitrión avisa a todos (la sala muere); el invitado, solo a él.
      if (onlineSideRef.current === "host") net.broadcast({ t: "bye" });
      else net.sendToHost({ t: "bye" });
    }
    net?.close();
    netRef.current = null;
    sessionRef.current = null;
    onlineSideRef.current = null;
    setRoleBoth(null);
    setQueueBoth([]);
    setLoserOverlay(false);
    setRoomNotice("");
    rotatedRef.current = false;
    currentMatchRef.current = null;
    clearHostRoom();
    if (joinRetryTimerRef.current) clearTimeout(joinRetryTimerRef.current);
    joinRetryTimerRef.current = null;
    joinRetriesRef.current = 0;
    setOnlineView("idle");
    setOnlineRtt(null);
    setRivalChar(null);
    setRematchWaiting(false);
    if (notice) setMenuNotice(notice);
    go("menu");
  }

  function quitToMenu() {
    if (matchRef.current?.mode === "online") leaveOnline();
    else {
      pausedRef.current = false;
      setPaused(false);
      go("menu");
    }
  }

  useEffect(() => {
    setStats(loadSave());
    setSelection(loadSelection());
    setMutedUi(isMuted());
    reduceRef.current = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const onVis = () => {
      if (document.visibilityState === "visible") {
        resumeAudio();
        // El fondo estático se pudo borrar al irse a segundo plano:
        // regenerarlo para que el escenario no quede incompleto.
        invalidateStaticLayer();
        // La sala del anfitrión se pudo caer al compartir: si el peer ya
        // no está registrado, volver a crearla con el mismo código.
        const net = netRef.current;
        if (
          net &&
          screenRef.current === "online" &&
          onlineSideRef.current === "host" &&
          !net.connected &&
          !net.registered &&
          roomCodeRef.current
        ) {
          createOnlineRoom(roomCodeRef.current);
        }
      } else keysRef.current.clear();
    };
    document.addEventListener("visibilitychange", onVis);
    // Desbloqueo de audio en cualquier toque (ver audio.ts): el anfitrión
    // online no toca nada cuando la partida arranca sola y se quedaba mudo.
    const unhookAudio = installAudioGestureUnlock();

    // Enlace de invitación (?room=XXXX): entrar directo como invitado.
    // Si no hay enlace, recuperar la sala del anfitrión si el navegador
    // recargó la pestaña al irse a segundo plano.
    const inviteCode = roomCodeFromSearch(window.location.search);
    if (inviteCode) {
      setSplash(false);
      const url = new URL(window.location.href);
      url.searchParams.delete("room");
      window.history.replaceState(null, "", url.toString());
      setMode("online");
      go("online");
      joinOnlineRoom(inviteCode);
    } else {
      const saved = loadHostRoom();
      if (saved) {
        setSplash(false);
        setMode("online");
        go("online");
        createOnlineRoom(saved);
      }
    }
    return () => {
      document.removeEventListener("visibilitychange", onVis);
      unhookAudio();
    };
  }, []);

  // Rotación al terminar el partido online: solo el anfitrión decide, y
  // solo si hay cola (sin cola sale la ventana actual). El guardado
  // `rotatedRef` hace que disparar dos veces sea inofensivo.
  const hudPhase = hud?.phase;
  const hudMode = hud?.mode;
  useEffect(() => {
    if (hudPhase === "over" && hudMode === "online" && onlineSideRef.current === "host") {
      maybeRotate();
    }
    // Solo importa el cambio de fase; maybeRotate lee refs.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [hudPhase]);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    // alpha:false: el cielo cubre todo el canvas, así el navegador no tiene
    // que mezclarlo con la página en cada frame.
    const ctx = canvas.getContext("2d", { alpha: false });
    if (!ctx) return;

    matchRef.current = createMatch({ mode: "demo", difficulty: "normal" });
    let acc = 0;
    let last = performance.now();
    let raf = 0;
    // Medidor de FPS (diagnóstico del lag): media móvil de 0.5 s.
    let fpsFrames = 0;
    let fpsSince = performance.now();
    let fpsShown = 0;

    // Tamaño del canvas: se lee con ResizeObserver, no en cada frame (leer
    // clientWidth/Height cada frame fuerza un reflow si React tocó el DOM).
    let cssW = 1;
    let cssH = 1;
    const parentEl = canvas.parentElement;
    const measure = () => {
      if (!parentEl) return;
      cssW = Math.max(1, parentEl.clientWidth);
      cssH = Math.max(1, parentEl.clientHeight);
    };
    measure();
    const ro = typeof ResizeObserver !== "undefined" ? new ResizeObserver(measure) : null;
    if (ro && parentEl) ro.observe(parentEl);
    else window.addEventListener("resize", measure);

    // Resolución dinámica: arranca en 1.5x (tope) y baja sola si el
    // dispositivo no sostiene los cuadros. Cada nivel recorta píxeles; el
    // dibujo es vectorial y casi no se nota. Solo baja (no oscila).
    const dprCap = Math.min(window.devicePixelRatio || 1, 1.5);
    let quality = 1; // multiplicador sobre dprCap
    let slowSince = 0;
    let slowMs = 0;
    let slowN = 0;
    const QUALITY_FLOOR = 0.6;

    const down = (e: KeyboardEvent) => {
      if (e.repeat) return;
      if (["Space", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].includes(e.code)) {
        e.preventDefault();
      }
      if (!keysRef.current.has(e.code)) keyAt.current[e.code] = performance.now();
      keysRef.current.add(e.code);
      if ((e.code === "KeyP" || e.code === "Escape") && screenRef.current === "match") {
        const m = matchRef.current;
        if (m && m.phase !== "over" && m.mode !== "online") {
          pausedRef.current = !pausedRef.current;
          setPaused(pausedRef.current);
        }
      }
      unlockAudio();
    };
    const up = (e: KeyboardEvent) => {
      keysRef.current.delete(e.code);
    };
    const onBlur = () => keysRef.current.clear();
    window.addEventListener("keydown", down);
    window.addEventListener("keyup", up);
    window.addEventListener("blur", onBlur);

    // QA hook, dev only: never exposed in production builds.
    if (import.meta.env.DEV) {
      window.__controlsTest = {
        setKeys: (codes: string[]) => {
          keysRef.current = new Set(codes);
          const now = performance.now();
          for (const c of codes) keyAt.current[c] = now;
        },
        getX: () => matchRef.current?.fighters[0]?.x ?? 0,
        getSpeed: () => Math.abs(matchRef.current?.fighters[0]?.vx ?? 0),
        getYaw: () => matchRef.current?.fighters[0]?.facing ?? 1,
        getMatch: () => matchRef.current,
        /**
         * Escenificar la vista de espectador (WebRTC no funciona en la VM,
         * así que la sala real no se puede probar aquí): pone un partido
         * en pantalla como espectador, con cola de ejemplo. `kind`:
         * "live" (barra + selector), "queued" (ya pedí turno, soy el #1),
         * "end" (ventana final de espectador), "loser" (overlay del
         * perdedor). Requiere un partido en curso (pulsar Jugar antes).
         */
        stageSpectator: (kind: "live" | "queued" | "end" | "loser") => {
          const m = matchRef.current;
          if (!m || screenRef.current !== "match") return false;
          // Sesión de espectador real sobre el partido en curso (para que
          // el panel sepa qué figuras están en cancha).
          if (!sessionRef.current) sessionRef.current = new OnlineSession(m, "guest", null);
          const inPlay = [m.fighters[0].character, m.fighters[1].character];
          const first = CHARACTERS.find((c) => !inPlay.includes(c.id));
          if (first) setSpectatorChar(first.id);
          setRoleBoth("spectator");
          setQueueBoth([
            { id: "peer-aaaa", char: "mango" },
            { id: "peer-bbbb", char: "kiwi" },
          ]);
          setLoserOverlay(false);
          if (kind === "queued") {
            // Red falsa solo para que myQueuePos me encuentre en la cola.
            netRef.current = {
              myId: "peer-aaaa",
              connected: false,
              registered: false,
              close: () => {},
            } as unknown as OnlineNet;
          } else if (kind === "end") {
            m.mode = "online";
            m.phase = "over";
          } else if (kind === "loser") {
            setLoserOverlay(true);
          }
          return true;
        },
      };
    }

    const keyOn = (codes: string[]) => codes.some((c) => keysRef.current.has(c));
    const keyTime = (codes: string[]) => codes.reduce((n, c) => Math.max(n, keyAt.current[c] ?? 0), 0);

    const buildPad = (human: "p0" | "p1"): { pad: Omit<InputPad, "jumpPressed" | "jumpReleased" | "attackPressed" | "attackReleased" | "downPressed">; jump: boolean; attack: boolean; down: boolean; jumpTaps: boolean } => {
      const touch = touchRef.current[human];
      const arrows = true;
      const wasd = true;
      const leftCodes = [
        ...(wasd ? ["KeyA"] : []),
        ...(arrows ? ["ArrowLeft"] : []),
      ];
      const rightCodes = [
        ...(wasd ? ["KeyD"] : []),
        ...(arrows ? ["ArrowRight"] : []),
      ];
      const jumpCodes = [
        ...(wasd ? ["KeyW", "Space"] : []),
        ...(arrows ? ["ArrowUp"] : []),
      ];
      const downCodes = [
        ...(wasd ? ["KeyS"] : []),
        ...(arrows ? ["ArrowDown"] : []),
      ];
      const atkCodes = ["KeyJ", "KeyK", "KeyX", "KeyF"];
      const left = touch.left || keyOn(leftCodes);
      const right = touch.right || keyOn(rightCodes);
      const jumpTaps = touch.jumpTaps > 0;
      const jump = touch.jump || jumpTaps || keyOn(jumpCodes);
      const attack = touch.attack || keyOn(atkCodes);
      const down = touch.down || keyOn(downCodes);
      const x = heldAxis(left, right, Math.max(touch.leftAt, keyTime(leftCodes)), Math.max(touch.rightAt, keyTime(rightCodes)));
      return { pad: { x, jump, attack, down }, jump, attack, down, jumpTaps };
    };

    const sample = (): Pads => {
      const a = buildPad("p0");
      const b = buildPad("p1");
      const was = wasRef.current;
      const pad = (side: typeof a, wj: boolean, wa: boolean, wd: boolean): InputPad => ({
        ...side.pad,
        jumpPressed: side.jump && !wj,
        jumpReleased: !side.jump && wj,
        attackPressed: side.attack && !wa,
        attackReleased: !side.attack && wa,
        downPressed: side.down && !wd,
      });
      return { p0: pad(a, was.j0, was.a0, was.d0), p1: pad(b, was.j1, was.a1, was.d1) };
    };

    const commit = () => {
      const a = buildPad("p0");
      const b = buildPad("p1");
      if (a.jumpTaps) touchRef.current.p0.jumpTaps = Math.max(0, touchRef.current.p0.jumpTaps - 1);
      if (b.jumpTaps) touchRef.current.p1.jumpTaps = Math.max(0, touchRef.current.p1.jumpTaps - 1);
      wasRef.current = { j0: a.jump, a0: a.attack, d0: a.down, j1: b.jump, a1: b.attack, d1: b.down };
    };

    const loop = (now: number) => {
      const frameMs = now - last;
      const dt = Math.min(0.05, frameMs / 1000);
      last = now;
      fpsFrames++;
      if (now - fpsSince >= 500) {
        const value = Math.round((fpsFrames * 1000) / (now - fpsSince));
        fpsSince = now;
        fpsFrames = 0;
        fpsShown = value;
        // El span se monta y desmonta con la pantalla de partido: escribir
        // siempre que el texto difiera, no solo cuando cambia el valor.
        const el = fpsElRef.current;
        // En online añade ping y retraso de entrada: si el juego "se siente
        // con lag", ahí se ve si es la red (ping alto) o el dispositivo (FPS).
        const sess = sessionRef.current;
        const text =
          modeRef.current === "online" && sess
            ? `${fpsShown} FPS · ${Math.round(netRef.current?.latency?.rtt ?? 0)} ms · d${sess.inputDelay}`
            : `${fpsShown} FPS`;
        if (el && el.textContent !== text) el.textContent = text;
      }

      // Calidad adaptativa: si durante ~1.5 s los frames promedian más de
      // 22 ms (por debajo de ~45 FPS), bajar la resolución un 15 %. Se
      // ignoran los frames enormes (pestaña en segundo plano, carga inicial).
      if (screenRef.current === "match" && frameMs < 250) {
        if (slowSince === 0) slowSince = now;
        slowMs += frameMs;
        slowN++;
        if (now - slowSince >= 1500) {
          if (slowMs / slowN > 22 && quality > QUALITY_FLOOR) {
            quality = Math.max(QUALITY_FLOOR, quality * 0.85);
          }
          slowSince = 0;
          slowMs = 0;
          slowN = 0;
        }
      } else {
        slowSince = 0;
        slowMs = 0;
        slowN = 0;
      }

      {
        // Tope de resolución 1.5: a 2x el canvas (780x1688 en un celular
        // 390x844) saturaba la GPU del teléfono y se veía el lag.
        const dpr = dprCap * quality;
        const bw = Math.floor(cssW * dpr);
        const bh = Math.floor(cssH * dpr);
        // No reallocar el canvas por 1-2 px de redondeo (la barra del
        // navegador móvil anima la altura y cada realloc pegaba un tirón).
        if (Math.abs(canvas.width - bw) > 2 || Math.abs(canvas.height - bh) > 2) {
          canvas.width = bw;
          canvas.height = bh;
        }
      }

      let m = matchRef.current;
      if (!m) {
        raf = requestAnimationFrame(loop);
        return;
      }
      if (screenRef.current === "menu" && (m.mode !== "demo" || m.phase === "over")) {
        m = createMatch({ mode: "demo", difficulty: "normal" });
        matchRef.current = m;
        interpRef.current.reset();
      }

      const playing = screenRef.current === "match" && !pausedRef.current;
      const simulating = screenRef.current === "menu" || playing;
      // Fracción de paso 120 Hz que sobra: se usa para interpolar el dibujo
      // entre el paso anterior y el actual (1 = dibujar el estado actual).
      let alpha = 1;
      if (simulating && m.phase !== "over") {
        if (m.mode === "online") {
          const session = sessionRef.current;
          if (session && session.match === m) {
            // Lockstep: mi pad se envía para pasos futuros; el partido
            // solo avanza cuando tengo el pad mío y el del rival. El
            // espectador no muestrea ni manda nada: solo simula con los
            // pads etiquetados que le reenvía el anfitrión.
            acc += dt;
            let n = 0;
            while (acc >= STEP && n < 8) {
              n++;
              acc -= STEP;
            }
            if (session.mySide !== null) {
              const pads = sample();
              const myPad = session.mySide === "p0" ? pads.p0 : pads.p1;
              const pkt = session.sendFrame(myPad, n);
              if (pkt) {
                const net = netRef.current;
                if (net) {
                  if (onlineSideRef.current === "host") {
                    // Al rival directo + a los espectadores, con mi lado.
                    net.sendToPlayers({ t: "pad", ...pkt });
                    net.sendToSpectators({ t: "pad", ...pkt, side: session.mySide });
                  } else {
                    net.sendToHost({ t: "pad", ...pkt });
                  }
                }
              }
              commit();
            }
            // Presupuesto de pasos: los del frame más hasta 4 de recuperación.
            // Tras un congelón de red el partido acelera un poco en vez de
            // saltar de golpe (antes corría hasta 12 pasos de una vez).
            session.runSteps(Math.min(session.backlog, n + 4));
            if (session.lastRan > 0) alpha = acc / STEP;
            const sync = `${session.step}:${session.hashLog.map((h) => `${h.step}=${h.hash}`).join(",")}`;
            if (session.step % 30 === 0 && sync !== lastSyncRef.current) {
              lastSyncRef.current = sync;
              arenaRef.current?.setAttribute("data-sync", sync);
              arenaRef.current?.setAttribute("data-online", session.side);
            }
          }
        } else {
          acc += dt;
          let guard = 0;
          let consumed = false;
          let stepped = false;
          const pads = m.mode === "demo" ? { p0: blankPad(), p1: blankPad() } : sample();
          while (acc >= STEP && guard++ < 8) {
            if (m.hitstop > 0) {
              m.hitstop -= STEP;
              acc -= STEP;
              continue;
            }
            interpRef.current.capture(m);
            const froze = stepMatch(m, consumed ? { p0: stripEdges(pads.p0), p1: stripEdges(pads.p1) } : pads, STEP);
            consumed = true;
            stepped = true;
            acc -= STEP;
            if (froze) break;
          }
          if (stepped) alpha = acc / STEP;
          if (consumed && m.mode !== "demo") commit();
        }
      } else {
        acc = 0;
      }

      m.shake = Math.max(0, m.shake - dt * (m.phase === "goal" ? 0.9 : 1.7));
      const noises = m.sfx.splice(0, 6);
      m.sfx.length = 0;
      for (const s of noises) playSfx(s.id, s.pan, s.vol ?? 1);

      // Tribuna dinámica: el murmullo sube con el peligro y estalla en el gol.
      if (screenRef.current === "match") {
        const level =
          m.phase === "goal" ? 1 : m.phase === "over" || pausedRef.current ? 0.15 : crowdDanger(m);
        setCrowdLevel(level);
      } else {
        setCrowdLevel(0);
      }

      // El espectador no guarda estadísticas (no jugó el partido).
      const spectating = m.mode === "online" && sessionRef.current?.mySide === null;
      if (screenRef.current === "match" && m.phase === "over" && !savedRef.current && m.mode !== "demo" && !spectating) {
        savedRef.current = true;
        const prev = loadSave();
        const session = sessionRef.current;
        const myScore =
          session && m.mode === "online" ? (session.mySide === "p0" ? m.scoreL : m.scoreR) : m.scoreL;
        const rivalScore =
          session && m.mode === "online" ? (session.mySide === "p0" ? m.scoreR : m.scoreL) : m.scoreR;
        const next: Save = {
          wins: prev.wins + (myScore > rivalScore ? 1 : 0),
          played: prev.played + 1,
          goals: prev.goals + myScore,
          best: Math.max(prev.best, myScore),
        };
        try {
          localStorage.setItem(SAVE_KEY, JSON.stringify(next));
        } catch {
          /* ignore */
        }
        setStats(next);
        if (myScore !== rivalScore) navigator.vibrate?.(myScore > rivalScore ? [20, 40, 20] : 16);
      }

      // Cámara propia: en online cada uno sigue a su luchador (el invitado
      // es p1); fuera de online siempre p0. Solo visual, no entra al hash.
      const focusControl = m.mode === "online" ? (sessionRef.current?.mySide ?? "p0") : "p0";
      const interp = interpRef.current;
      const lerped = interp.apply(m, alpha);
      try {
        drawMatch(ctx, m, canvas.width, canvas.height, now / 1000, dt, reduceRef.current, focusControl);
      } finally {
        if (lerped) interp.restore(m);
      }

      if (screenRef.current === "match") {
        const time = Math.ceil(m.time);
        const prev = hudSnap.current;
        const changed =
          !prev ||
          prev.scoreL !== m.scoreL ||
          prev.scoreR !== m.scoreR ||
          prev.time !== time ||
          prev.phase !== m.phase ||
          prev.sudden !== m.sudden ||
          prev.banner !== m.banner ||
          prev.mode !== m.mode ||
          prev.leftName !== (m.fighters[0]?.name ?? "Jugador 1") ||
          prev.rightName !== (m.fighters[1]?.name ?? "Jugador 2");
        if (changed) {
          if (prev && (prev.scoreL !== m.scoreL || prev.scoreR !== m.scoreR)) {
            setLive(
              `Marcador. ${m.fighters[0]?.name ?? "Jugador 1"} ${m.scoreL}, ` +
                `${m.fighters[1]?.name ?? "Jugador 2"} ${m.scoreR}. ${m.banner || ""}`,
            );
            if (m.phase === "goal") navigator.vibrate?.(28);
          }
          const next: Hud = {
            scoreL: m.scoreL,
            scoreR: m.scoreR,
            time,
            phase: m.phase,
            sudden: m.sudden,
            banner: m.banner,
            mode: m.mode,
            leftName: m.fighters[0]?.name ?? "Jugador 1",
            rightName: m.fighters[1]?.name ?? "Jugador 2",
          };
          hudSnap.current = next;
          setHud(next);
        }
      }

      raf = requestAnimationFrame(loop);
    };

    raf = requestAnimationFrame(loop);
    return () => {
      cancelAnimationFrame(raf);
      ro?.disconnect();
      window.removeEventListener("resize", measure);
      window.removeEventListener("keydown", down);
      window.removeEventListener("keyup", up);
      window.removeEventListener("blur", onBlur);
      netRef.current?.close();
      if (import.meta.env.DEV) delete window.__controlsTest;
    };
  }, []);

  const showDock = screen === "match" && hud?.phase !== "over" && onlineRole !== "spectator";
  const clock = hud?.sudden ? "ORO" : fmt(hud?.time ?? 0);
  const leftChoice = getCharacter(selection.left);
  const rightChoice = getCharacter(selection.right);

  function openRoster(slot: FighterSlot) {
    rosterFromRef.current = screenRef.current;
    setActiveSlot(slot);
    setRosterNotice("");
    unlockAudio();
    playSfx("ui", 0, 0.7);
    go("roster");
  }

  function myPickCard(side: "host" | "guest") {
    const slot: FighterSlot = side === "host" ? "left" : "right";
    const choice = slot === "left" ? leftChoice : rightChoice;
    const locked = onlineView === "connected";
    return (
      <button
        type="button"
        className="pick-card pick-sol"
        disabled={locked}
        onClick={() => openRoster(slot)}
        aria-label={`Tu figura: ${choice.name}`}
      >
        <CharacterPreview id={selection[slot]} />
        <span>Tú {side === "host" ? "(izquierda)" : "(derecha)"}</span>
        <strong>{choice.name}</strong>
      </button>
    );
  }

  function rivalPickCard() {
    if (!rivalChar) return <p className="keys-hint">Rival: figura por confirmar…</p>;
    return (
      <div className="pick-card pick-luna">
        <CharacterPreview id={rivalChar} />
        <span>Rival</span>
        <strong>{getCharacter(rivalChar).name}</strong>
      </div>
    );
  }

  /** Mi puesto en la cola (1 = el siguiente), o null si no estoy en cola. */
  function myQueuePos(): number | null {
    const me = netRef.current?.myId;
    if (!me) return null;
    const idx = queue.findIndex((e) => e.id === me);
    return idx >= 0 ? idx + 1 : null;
  }

  /** Panel de la cola de turnos (vista de espectador y pantalla de sala). */
  function queuePanel() {
    const session = sessionRef.current;
    const inPlay = session
      ? [session.match.fighters[0].character, session.match.fighters[1].character]
      : [];
    const pos = myQueuePos();
    return (
      <div className="queue-panel">
        {queue.length > 0 ? (
          <p className="keys-hint" aria-live="polite">
            En cola:{" "}
            {queue.map((e, i) => (
              <span key={e.id} className="queue-chip">
                #{i + 1} {getCharacter(e.char).name}
              </span>
            ))}
          </p>
        ) : (
          <p className="keys-hint">Nadie esperando turno.</p>
        )}
        {onlineRole === "spectator" &&
          (pos !== null ? (
            <>
              <p className="online-notice" role="status">
                Eres el #{pos} en la cola. Juegas cuando termine el partido en curso.
              </p>
              <button type="button" className="ghost-btn" onClick={cancelTurn}>
                Cancelar mi turno
              </button>
            </>
          ) : (
            <>
              <p className="keys-hint">Elige tu figura y pide turno:</p>
              <div className="spec-pick-row" role="group" aria-label="Tu figura para el turno">
                {CHARACTERS.map((c) => {
                  const taken = inPlay.includes(c.id);
                  return (
                    <button
                      key={c.id}
                      type="button"
                      className={`spec-pick${spectatorChar === c.id ? " on" : ""}${taken ? " used" : ""}`}
                      disabled={taken}
                      aria-pressed={spectatorChar === c.id}
                      aria-label={taken ? `${c.name} (en cancha)` : c.name}
                      onClick={() => setSpectatorChar(c.id)}
                    >
                      <CharacterPreview id={c.id} />
                    </button>
                  );
                })}
              </div>
              <button type="button" className="play-btn" onClick={requestTurn}>
                Pedir turno
              </button>
            </>
          ))}
      </div>
    );
  }

  function persistSelection(next: Selection) {
    try {
      localStorage.setItem(SELECTION_KEY, JSON.stringify(next));
    } catch {
      // La selección sigue funcionando en memoria si el navegador la bloquea.
    }
  }

  function chooseCharacter(id: CharacterId) {
    const other =
      screenRef.current === "online"
        ? rivalChar
        : activeSlot === "left"
          ? selection.right
          : selection.left;
    if (id === other) {
      setRosterNotice(`${getCharacter(id).name} ya está elegido para el otro lado.`);
      return;
    }
    const next = { ...selection, [activeSlot]: id };
    setSelection(next);
    persistSelection(next);
    setRosterNotice(`${getCharacter(id).name} entra a la cancha.`);
    playSfx("ui", 0, 0.65);
  }

  function randomizeRival() {
    const nextId = randomCharacterId(selection.left);
    const next = { ...selection, right: nextId };
    setSelection(next);
    persistSelection(next);
    setRosterNotice(`Rival al azar: ${getCharacter(nextId).name}.`);
    playSfx("ui", 0, 0.65);
  }

  return (
    <div className="shell">
      <div className="arena" ref={arenaRef}>
        <canvas ref={canvasRef} className="pitch" aria-label="Cancha de Goal Fighters" />
        <p className="sr-only" aria-live="polite">
          {live}
        </p>

        {screen === "match" && hud && (
          <header className="hud">
            <div className="score score-sol">
              <span>{hud.leftName}</span>
              <strong>{hud.scoreL}</strong>
            </div>
            <div className="clock-wrap">
              {hud.mode === "online" ? (
                <button
                  type="button"
                  className="icon-btn"
                  aria-label="Abandonar partida online"
                  onClick={() => leaveOnline()}
                >
                  <X />
                </button>
              ) : (
                <button
                  type="button"
                  className="icon-btn"
                  aria-label={paused ? "Reanudar" : "Pausa"}
                  onClick={() => {
                    if (hud.phase === "over") return;
                    pausedRef.current = !pausedRef.current;
                    setPaused(pausedRef.current);
                    unlockAudio();
                  }}
                >
                  {paused ? <Play /> : <Pause />}
                </button>
              )}
              <span className="clock-col">
                <time className={hud.sudden ? "clock gold" : "clock"}>{clock}</time>
                <span className="fps-meter" ref={fpsElRef} />
              </span>
              <button
                type="button"
                className="icon-btn"
                aria-label={muted ? "Activar sonido" : "Silenciar"}
                onClick={() => {
                  unlockAudio();
                  setMutedUi(toggleMute());
                }}
              >
                {muted ? <VolumeX /> : <Volume2 />}
              </button>
            </div>
            <div className="score score-luna">
              <span>{hud.rightName}</span>
              <strong>{hud.scoreR}</strong>
            </div>
          </header>
        )}

        {screen === "menu" && !splash && (
          <div className="overlay menu-screen">
            <header className="menu-top">
              <span className="chip-stat" aria-label={`Victorias: ${stats.wins}`}>
                <Trophy aria-hidden="true" />
                {stats.wins}
              </span>
              <div className="menu-top-actions">
                <button type="button" className="round-btn" aria-label="Cómo se juega" onClick={() => go("help")}>
                  <CircleHelp />
                </button>
                <button
                  type="button"
                  className="round-btn"
                  aria-label={muted ? "Activar sonido" : "Silenciar"}
                  onClick={() => {
                    unlockAudio();
                    setMutedUi(toggleMute());
                  }}
                >
                  {muted ? <VolumeX /> : <Volume2 />}
                </button>
              </div>
            </header>

            <GameLogo />

            {menuNotice && (
              <p className="online-notice menu-notice" role="status">
                {menuNotice}
              </p>
            )}

            <div className="mode-tabs" role="group" aria-label="Modo de juego">
              {(
                [
                  ["cpu", "1 vs CPU"],
                  ["online", "Online 1 vs 1"],
                ] as const
              ).map(([id, label]) => (
                <button
                  key={id}
                  type="button"
                  className={mode === id ? "mode-tab on" : "mode-tab"}
                  onClick={() => setMode(id)}
                >
                  {label}
                </button>
              ))}
            </div>

            {mode === "online" ? (
              <div className="online-hero">
                <div className="online-hero-art" aria-hidden="true">
                  <CharacterPreview id={selection.left} size="lg" />
                  <span className="vs-badge">VS</span>
                  <div className="mystery-rival">?</div>
                </div>
                <p className="lede">Crea una sala y comparte el enlace, o entra con el código de un amigo.</p>
                <button
                  type="button"
                  className="cta-btn"
                  onClick={() => {
                    setMenuNotice("");
                    setOnlineView("idle");
                    setOnlineError("");
                    go("online");
                  }}
                >
                  <Users aria-hidden="true" />
                  Ir a la sala
                </button>
              </div>
            ) : (
              <>
                <div className="showdown" role="group" aria-label="Personajes elegidos">
                  <button
                    type="button"
                    className="hero-pick hero-sol"
                    onClick={() => openRoster("left")}
                    aria-label={`Elegir tu personaje: ${leftChoice.name}`}
                  >
                    <span className="pedestal" aria-hidden="true" />
                    <CharacterPreview id={selection.left} size="lg" />
                    <span className="hero-tag">Tú</span>
                    <strong>{leftChoice.name}</strong>
                    <span className="hero-change">Cambiar</span>
                  </button>
                  <span className="vs-badge" aria-hidden="true">
                    VS
                  </span>
                  <button
                    type="button"
                    className="hero-pick hero-luna"
                    onClick={() => openRoster("right")}
                    aria-label={`Elegir el rival: ${rightChoice.name}`}
                  >
                    <span className="pedestal" aria-hidden="true" />
                    <CharacterPreview id={selection.right} size="lg" facing={-1} team="right" />
                    <span className="hero-tag">Rival CPU</span>
                    <strong>{rightChoice.name}</strong>
                    <span className="hero-change">Cambiar</span>
                  </button>
                </div>

                <div className="diff-chips" role="group" aria-label="Dificultad">
                  {(
                    [
                      ["easy", "Fácil"],
                      ["normal", "Normal"],
                      ["hard", "Duro"],
                    ] as const
                  ).map(([id, label]) => (
                    <button
                      key={id}
                      type="button"
                      className={difficulty === id ? "diff-chip on" : "diff-chip"}
                      onClick={() => setDifficulty(id)}
                    >
                      {label}
                    </button>
                  ))}
                </div>

                <button type="button" className="cta-btn" onClick={startMatch}>
                  <Play aria-hidden="true" />
                  Jugar
                </button>
              </>
            )}

            <nav className="menu-tiles" aria-label="Más opciones">
              <button type="button" className="tile-btn" onClick={() => openRoster("left")}>
                <span className="tile-art" aria-hidden="true">
                  <CharacterPreview id={selection.left === "kiwi" ? "pico" : "kiwi"} size="sm" />
                </span>
                Figuras
                <small>8 luchadores</small>
              </button>
              <button type="button" className="tile-btn" onClick={() => go("help")}>
                <span className="tile-art tile-help" aria-hidden="true">
                  ?
                </span>
                Cómo jugar
                <small>Controles y trucos</small>
              </button>
            </nav>
            <p className="keys-hint menu-keys">A D mover · W saltar / hover · J golpear · S plancha</p>
          </div>
        )}

        {splash && <SplashScreen onStart={() => {
          unlockAudio();
          playSfx("ui", 0, 0.8);
          setSplash(false);
        }} />}

        {screen === "online" && (
          <div className="overlay">
            <section className="card menu-card">
              <p className="eyebrow">Online 1 vs 1</p>
              <h1>Sala online</h1>
              {onlineView === "idle" && (
                <>
                  <p className="lede">Crea una sala y comparte el enlace, o entra a la sala de tu rival.</p>
                  <button type="button" className="play-btn" onClick={() => createOnlineRoom()}>
                    Crear sala
                  </button>
                  <div className="join-row">
                    <input
                      type="text"
                      className="code-input"
                      placeholder="Código"
                      value={joinCode}
                      maxLength={4}
                      autoCapitalize="characters"
                      autoComplete="off"
                      onChange={(e) => setJoinCode(e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, ""))}
                      aria-label="Código de la sala"
                    />
                    <button type="button" className="play-btn" onClick={() => joinOnlineRoom()}>
                      Unirse
                    </button>
                  </div>
                  {onlineError && (
                    <p className="online-error" role="alert">
                      {onlineError}
                    </p>
                  )}
                  <button type="button" className="ghost-btn" onClick={() => go("menu")}>
                    Atrás
                  </button>
                </>
              )}
              {onlineView === "waiting" && (
                <>
                  {roomNotice && (
                    <p className="online-notice" role="status">
                      {roomNotice}
                    </p>
                  )}
                  <p className="lede">Pásale el enlace a tu rival, o el código:</p>
                  <p className="room-code" aria-live="polite">
                    {roomCode}
                  </p>
                  <button type="button" className="play-btn" onClick={shareRoomLink}>
                    Compartir enlace
                  </button>
                  <input
                    type="text"
                    className="room-link"
                    readOnly
                    value={roomInviteLink(roomCode)}
                    onFocus={(e) => e.target.select()}
                    aria-label="Enlace de la sala"
                  />
                  {shareNote && (
                    <p className="online-notice" role="status">
                      {shareNote}
                    </p>
                  )}
                  <p className="keys-hint">Quien abra el enlace entra directo a la sala.</p>
                  <p className="keys-hint">Esperando a que entre tu rival…</p>
                  {onlineRole === "player" ? (
                    <div className="versus-pick" role="group" aria-label="Figuras de la sala">
                      {myPickCard(onlineSideRef.current === "host" ? "host" : "guest")}
                      <span className="versus-mark">VS</span>
                      {rivalPickCard()}
                    </div>
                  ) : (
                    <p className="keys-hint">Estás de espectador en esta sala.</p>
                  )}
                  {(netRef.current?.spectatorIds().length ?? 0) > 0 && (
                    <p className="keys-hint">
                      {netRef.current?.spectatorIds().length} espectando ahora mismo.
                    </p>
                  )}
                  {queuePanel()}
                  <button
                    type="button"
                    className="ghost-btn"
                    onClick={cancelOnline}
                  >
                    Cancelar
                  </button>
                </>
              )}
              {onlineView === "spectating" && (
                <>
                  {roomNotice && (
                    <p className="online-notice" role="status">
                      {roomNotice}
                    </p>
                  )}
                  <p className="lede">
                    Estás de espectador en la sala {roomCode}. Cuando empiece el partido lo ves en vivo aquí mismo.
                  </p>
                  <p className="keys-hint">El primero en entrar juega; los demás miran y piden turno.</p>
                  {queuePanel()}
                  <button type="button" className="ghost-btn" onClick={cancelOnline}>
                    Salir de la sala
                  </button>
                </>
              )}
              {onlineView === "joining" && (
                <>
                  <p className="lede">Conectando a la sala {roomCode}…</p>
                  <div className="versus-pick" role="group" aria-label="Tu figura">
                    {myPickCard("guest")}
                    <span className="versus-mark">VS</span>
                    {rivalPickCard()}
                  </div>
                  <p className="keys-hint">Toca tu figura para cambiarla mientras conecta.</p>
                  <button
                    type="button"
                    className="ghost-btn"
                    onClick={cancelOnline}
                  >
                    Cancelar
                  </button>
                </>
              )}
              {onlineView === "connected" && (
                <>
                  <p className="lede">¡Rival conectado! Arranca el partido…</p>
                  <p className="keys-hint">
                    {onlineRtt !== null ? `Ping ${onlineRtt} ms` : "Midiendo conexión…"}
                  </p>
                  <div className="versus-pick" role="group" aria-label="Figuras de la sala">
                    {myPickCard(onlineSideRef.current === "host" ? "host" : "guest")}
                    <span className="versus-mark">VS</span>
                    {rivalPickCard()}
                  </div>
                </>
              )}
              {onlineView === "error" && (
                <>
                  <p className="online-error" role="alert">
                    {onlineError || "No se pudo conectar."}
                  </p>
                  <button type="button" className="play-btn" onClick={() => setOnlineView("idle")}>
                    Intentar de nuevo
                  </button>
                  <button type="button" className="ghost-btn" onClick={() => go("menu")}>
                    Atrás
                  </button>
                </>
              )}
            </section>
          </div>
        )}

        {screen === "roster" && (
          <div className="overlay roster-overlay">
            <section className="card roster-card">
              <div className="roster-head">
                <div>
                  <p className="eyebrow">Colección Goal Fighters</p>
                  <h1>Elige tu figura</h1>
                </div>
                <button type="button" className="icon-btn" aria-label="Cerrar selección" onClick={() => go("menu")}>
                  <X />
                </button>
              </div>
              <div className="roster-tabs" role="tablist" aria-label="Lado a elegir">
                {(["left", "right"] as const).map((slot) => {
                  const chosen = slot === "left" ? leftChoice : rightChoice;
                  const label = slot === "left" ? (mode === "cpu" ? "Tú" : "Jugador 1") : mode === "cpu" ? "Rival CPU" : "Jugador 2";
                  return (
                    <button
                      key={slot}
                      type="button"
                      role="tab"
                      aria-selected={activeSlot === slot}
                      className={activeSlot === slot ? "roster-tab on" : "roster-tab"}
                      onClick={() => {
                        if (screenRef.current === "online") {
                          const mySlot: FighterSlot = onlineSideRef.current === "host" ? "left" : "right";
                          if (slot !== mySlot) return;
                        }
                        setActiveSlot(slot);
                        setRosterNotice("");
                      }}
                    >
                      <span>{label}</span>
                      <strong>{chosen.name}</strong>
                    </button>
                  );
                })}
              </div>
              <div className="roster-grid">
                {CHARACTERS.map((character) => {
                  const chosenHere = selection[activeSlot] === character.id;
                  const usedElsewhere =
                    screenRef.current === "online"
                      ? rivalChar === character.id
                      : (activeSlot === "left" ? selection.right : selection.left) === character.id;
                  return (
                    <button
                      key={character.id}
                      type="button"
                      className={`roster-figure${chosenHere ? " on" : ""}${usedElsewhere ? " used" : ""}`}
                      aria-pressed={chosenHere}
                      disabled={usedElsewhere}
                      onClick={() => chooseCharacter(character.id)}
                    >
                      <CharacterPreview id={character.id} />
                      <strong>{character.name}</strong>
                      <small>{usedElsewhere ? "En cancha" : chosenHere ? "Elegido" : "Elegir"}</small>
                    </button>
                  );
                })}
              </div>
              <p className="roster-notice" aria-live="polite">
                {rosterNotice || "Toca una figura para cambiar el lado activo."}
              </p>
              {activeSlot === "right" && screenRef.current !== "online" && (
                <button type="button" className="ghost-btn" onClick={randomizeRival}>
                  Rival al azar
                </button>
              )}
              <button type="button" className="play-btn" onClick={() => go(rosterFromRef.current)}>
                Listo
              </button>
            </section>
          </div>
        )}

        {screen === "help" && (
          <div className="overlay">
            <section className="card">
              <p className="eyebrow">Reglas de la cancha</p>
              <h1>Cómo se juega</h1>
              <ul className="help">
                <li>1 contra 1: marca el gol en la ventana elevada rival y defiende la tuya sin portero.</li>
                <li>La portería no toca el suelo: el balón solo entra entre el larguero y el borde inferior.</li>
                <li>Corre, salta y mantén SALTAR para hacer hover. Intercepta con patada, cabezazo o plancha.</li>
                <li>GOLPE dispara el balón; mantenlo pulsado para cargarlo. Los tiros altos y los rebotes son la clave.</li>
                <li>PLANCHA en el aire cae en picado. Al aterrizar, la onda despeja el balón.</li>
                <li>Dos minutos de 1 vs 1. Si empatan, gol de oro.</li>
              </ul>
              <button type="button" className="play-btn" onClick={() => go("menu")}>
                Listo
              </button>
            </section>
          </div>
        )}

        {screen === "match" && paused && hud?.phase !== "over" && (
          <div className="overlay">
            <section className="card card-slim">
              <h1>Pausa</h1>
              <button
                type="button"
                className="play-btn"
                onClick={() => {
                  pausedRef.current = false;
                  setPaused(false);
                }}
              >
                Reanudar
              </button>
              <button type="button" className="ghost-btn" onClick={startMatch}>
                Reiniciar
              </button>
              <button
                type="button"
                className="ghost-btn"
                onClick={() => {
                  pausedRef.current = false;
                  setPaused(false);
                  go("menu");
                }}
              >
                Menú
              </button>
            </section>
          </div>
        )}

        {screen === "match" && hud?.phase === "over" && (
          <div className="overlay">
            <section className="card card-slim">
              <p className="eyebrow">Fin del partido</p>
              <h1>
                {hud.scoreL === hud.scoreR
                  ? "Empate"
                  : hud.scoreL > hud.scoreR
                    ? `Gana ${hud.leftName}`
                    : `Gana ${hud.rightName}`}
              </h1>
              <p className="final-score">
                <span className="sol-ink">{hud.scoreL}</span>
                <span className="dash">–</span>
                <span className="luna-ink">{hud.scoreR}</span>
              </p>
              {hud.mode === "online" && onlineRole === "spectator" ? (
                <>
                  <p className="lede">El siguiente partido arranca solo cuando haya retador.</p>
                  {queuePanel()}
                </>
              ) : hud.mode === "online" ? (
                <button type="button" className="play-btn" onClick={requestRematch} disabled={rematchWaiting}>
                  {rematchWaiting ? "Esperando revancha…" : "Revancha"}
                </button>
              ) : (
                <button type="button" className="play-btn" onClick={startMatch}>
                  Otra vez
                </button>
              )}
              <button type="button" className="ghost-btn" onClick={quitToMenu}>
                Menú
              </button>
            </section>
          </div>
        )}

        {loserOverlay && screen === "match" && (
          <div className="overlay">
            <section className="card card-slim">
              <p className="eyebrow">Perdiste el partido</p>
              <h1>¿Te quedas de espectador?</h1>
              <p className="lede">
                El ganador sigue en cancha contra el siguiente retador. Puedes quedarte viendo el partido y pedir turno
                para volver a jugar.
              </p>
              <button type="button" className="play-btn" onClick={() => setLoserOverlay(false)}>
                Quedarme viendo
              </button>
              <button type="button" className="ghost-btn" onClick={() => leaveOnline()}>
                Salir al menú
              </button>
            </section>
          </div>
        )}
      </div>

      {screen === "match" && onlineRole === "spectator" && hud?.phase !== "over" && (
        <div className="spec-bar">
          <span className="spec-badge">Espectador · en vivo</span>
          {queuePanel()}
        </div>
      )}

      {showDock && (
        <div className="dock">
          {mode === "online" ? (
            sessionRef.current?.mySide === "p1" ? (
              <PadBlock label="Tú" hints={["←", "→", "↑", "L"]} onHold={(k, d) => setHold("p1", k, d)} />
            ) : (
              <PadBlock label="Tú" hints={["A", "D", "W", "J"]} onHold={(k, d) => setHold("p0", k, d)} />
            )
          ) : (
            <PadBlock
              label="Tú"
              hints={["A", "D", "W", "J"]}
              onHold={(k, d) => setHold("p0", k, d)}
            />
          )}
        </div>
      )}
    </div>
  );
}

const PREVIEW_SIZES = {
  sm: { w: 84, h: 94, scale: 1.08 },
  lg: { w: 150, h: 160, scale: 1.85 },
} as const;

function CharacterPreview({
  id,
  size = "sm",
  facing = 1,
  team = "left",
  action = "idle",
  className = "fighter-preview",
}: {
  id: CharacterId;
  size?: keyof typeof PREVIEW_SIZES;
  facing?: 1 | -1;
  team?: "left" | "right";
  action?: PreviewAction;
  className?: string;
}) {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    const { w, h, scale } = PREVIEW_SIZES[size];
    canvas.width = w * dpr;
    canvas.height = h * dpr;
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);

    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const start = performance.now();
    let raf = 0;

    const paint = (now: number) => {
      ctx.clearRect(0, 0, w, h);
      drawCharacterPreview(ctx, id, w / 2, h - 6 - 34 * scale, scale, (now - start) / 1000, { facing, team, action });
      if (!reduce) raf = requestAnimationFrame(paint);
    };
    paint(start);

    return () => cancelAnimationFrame(raf);
  }, [id, size, facing, team, action]);

  return <canvas ref={canvasRef} className={`${className} preview-${size}`} aria-hidden="true" />;
}

/** Balón de fútbol vectorial (logo, splash). */
function SoccerBall({ className }: { className?: string }) {
  return (
    <svg viewBox="0 0 100 100" className={className} aria-hidden="true">
      <defs>
        <clipPath id="ball-clip">
          <circle cx="50" cy="50" r="46" />
        </clipPath>
      </defs>
      <circle cx="50" cy="50" r="46" fill="#fffdf6" />
      <g clipPath="url(#ball-clip)" fill="#21151f" stroke="#21151f" strokeWidth="3" strokeLinejoin="round">
        <polygon points="50.00,35.00 64.27,45.36 58.82,62.14 41.18,62.14 35.73,45.36" />
        <polygon points="50.00,18.00 39.54,10.40 43.53,-1.90 56.47,-1.90 60.46,10.40" />
        <line x1="50.00" y1="35.00" x2="50.00" y2="18.00" />
        <polygon points="80.43,40.11 84.43,27.81 97.36,27.81 101.36,40.11 90.90,47.71" />
        <line x1="64.27" y1="45.36" x2="80.43" y2="40.11" />
        <polygon points="68.81,75.89 81.74,75.89 85.74,88.19 75.27,95.79 64.81,88.19" />
        <line x1="58.82" y1="62.14" x2="68.81" y2="75.89" />
        <polygon points="31.19,75.89 35.19,88.19 24.73,95.79 14.26,88.19 18.26,75.89" />
        <line x1="41.18" y1="62.14" x2="31.19" y2="75.89" />
        <polygon points="19.57,40.11 9.10,47.71 -1.36,40.11 2.64,27.81 15.57,27.81" />
        <line x1="35.73" y1="45.36" x2="19.57" y2="40.11" />
        <line x1="60.46" y1="10.40" x2="84.43" y2="27.81" />
        <line x1="90.90" y1="47.71" x2="81.74" y2="75.89" />
        <line x1="64.81" y1="88.19" x2="35.19" y2="88.19" />
        <line x1="18.26" y1="75.89" x2="9.10" y2="47.71" />
        <line x1="15.57" y1="27.81" x2="39.54" y2="10.40" />
        <ellipse cx="50" cy="96" rx="60" ry="22" fill="rgba(33,21,31,0.18)" stroke="none" />
      </g>
      <ellipse cx="34" cy="26" rx="10" ry="6" fill="rgba(255,255,255,0.85)" transform="rotate(-30 34 26)" />
      <circle cx="50" cy="50" r="46" fill="none" stroke="#21151f" strokeWidth="6" />
    </svg>
  );
}

/** Logo del juego: tipografía del juego (Lilita One) con relieve y balón. */
function GameLogo({ big = false }: { big?: boolean }) {
  return (
    <div className={big ? "game-logo big" : "game-logo"} role="img" aria-label="Goal Fighters">
      <span className="logo-line logo-goal">
        G<SoccerBall className="logo-ball" />AL
      </span>
      <span className="logo-line logo-fighter">FIGHTERS</span>
      <span className="logo-ribbon">Fútbol · Golpes · Gloria</span>
    </div>
  );
}

/** Pantalla de arranque estilo app móvil: carga breve y "toca para empezar". */
function SplashScreen({ onStart }: { onStart: () => void }) {
  const [ready, setReady] = useState(false);
  useEffect(() => {
    const t = setTimeout(() => setReady(true), 1300);
    return () => clearTimeout(t);
  }, []);
  return (
    <div
      className={ready ? "splash ready" : "splash"}
      role="button"
      tabIndex={0}
      aria-label="Toca para empezar"
      onClick={() => ready && onStart()}
      onKeyDown={(e) => {
        if (ready && (e.key === "Enter" || e.key === " ")) onStart();
      }}
    >
      <div className="splash-rays" aria-hidden="true" />
      <GameLogo big />
      <div className="splash-fighters" aria-hidden="true">
        <CharacterPreview id="tizo" size="lg" action="combo" className="splash-fighter" />
        <SoccerBall className="splash-ball" />
        <CharacterPreview id="lumi" size="lg" facing={-1} team="right" action="combo" className="splash-fighter" />
      </div>
      <div className="splash-bottom">
        {ready ? (
          <p className="tap-start">Toca para empezar</p>
        ) : (
          <div className="load-bar" aria-hidden="true">
            <span />
          </div>
        )}
        <p className="splash-credit">8 figuras · 1 vs CPU · Online</p>
      </div>
    </div>
  );
}

function PadBlock({
  label,
  hints,
  onHold,
}: {
  label: string;
  hints: [string, string, string, string];
  onHold: (key: HoldKey, down: boolean) => void;
}) {
  return (
    <div className="pad-block">
      <span className="pad-label">{label}</span>
      <div className="pad-grid">
        <Hold label="" aria="Izquierda" hint={hints[0]} className="b-left" onHold={(d) => onHold("left", d)}>
          <ChevronLeft />
        </Hold>
        <Hold label="" aria="Derecha" hint={hints[1]} className="b-right" onHold={(d) => onHold("right", d)}>
          <ChevronRight />
        </Hold>
        <Hold label="Saltar" aria="Saltar" hint={hints[2]} className="b-jump" onHold={(d) => onHold("jump", d)} />
        <Hold label="Golpe" aria="Golpe" hint={hints[3]} className="b-punch" onHold={(d) => onHold("attack", d)} />
      </div>
    </div>
  );
}

function Hold({
  label,
  aria,
  hint,
  className,
  onHold,
  children,
}: {
  label: string;
  aria: string;
  hint: string;
  className: string;
  onHold: (down: boolean) => void;
  children?: ReactNode;
}) {
  return (
    <button
      type="button"
      className={`padbtn ${className}`}
      aria-label={aria}
      onContextMenu={(e) => e.preventDefault()}
      onPointerDown={(e) => {
        e.preventDefault();
        e.currentTarget.setPointerCapture(e.pointerId);
        onHold(true);
      }}
      onPointerUp={() => onHold(false)}
      onPointerCancel={() => onHold(false)}
      onLostPointerCapture={() => onHold(false)}
    >
      {children}
      {label ? <span>{label}</span> : null}
      <kbd className="hint">{hint}</kbd>
    </button>
  );
}

declare global {
  interface Window {
    __controlsTest?: {
      getYaw: () => number;
      getSpeed: () => number;
      getX: () => number;
      getMatch: () => Match | null;
      setKeys: (codes: string[]) => void;
      stageSpectator: (kind: "live" | "queued" | "end" | "loser") => boolean;
    };
  }
}
