import type { Match, SfxId } from "./engine";
import { WORLD } from "./constants.ts";
import { migrateStorageKeys, STORAGE_KEYS } from "../lib/storage-keys.ts";

type Bus = {
  ctx: AudioContext | null;
  master: GainNode | null;
  music: GainNode | null;
  sfx: GainNode | null;
  musicSrc: AudioBufferSourceNode | null;
  muted: boolean;
};

/** Preferencia de silencio guardada, leída al cargar (antes solo se leía al primer toque y el botón mostraba mal el estado). */
function savedMuted(): boolean {
  try {
    if (typeof localStorage === "undefined") return false;
    migrateStorageKeys();
    return localStorage.getItem(STORAGE_KEYS.mute) === "1";
  } catch {
    return false;
  }
}

const bus: Bus = { ctx: null, master: null, music: null, sfx: null, musicSrc: null, muted: savedMuted() };

function ctx(): AudioContext | null {
  return bus.ctx;
}

export function isMuted() {
  return bus.muted;
}

export function setMuted(muted: boolean) {
  bus.muted = muted;
  const c = ctx();
  if (c && bus.master) {
    bus.master.gain.setTargetAtTime(muted ? 0 : 1, c.currentTime, 0.02);
  }
  try {
    localStorage.setItem(STORAGE_KEYS.mute, muted ? "1" : "0");
  } catch {
    /* ignore */
  }
}

export function toggleMute() {
  setMuted(!bus.muted);
  return bus.muted;
}

export function unlockAudio() {
  const AC = window.AudioContext || (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;
  if (!bus.ctx) {
    const c = new AC();
    const master = c.createGain();
    const music = c.createGain();
    const sfx = c.createGain();
    music.gain.value = 0.22;
    sfx.gain.value = 0.85;
    music.connect(master);
    sfx.connect(master);
    master.connect(c.destination);
    bus.ctx = c;
    bus.master = master;
    bus.music = music;
    bus.sfx = sfx;
    try {
      migrateStorageKeys();
      bus.muted = localStorage.getItem(STORAGE_KEYS.mute) === "1";
    } catch {
      bus.muted = false;
    }
    master.gain.value = bus.muted ? 0 : 1;
    // La música se sintetiza muestra a muestra (~4 s de audio): hacerlo en
    // el mismo tap que arranca el partido congelaba el primer segundo.
    setTimeout(() => {
      if (bus.ctx === c && !bus.musicSrc) {
        try {
          startMusic(c, music);
        } catch {
          /* sin música */
        }
      }
      prewarmAudio(c);
    }, 120);
  }
  resumeAudio();
}

export function resumeAudio() {
  // "interrupted" es el estado de iOS tras llamadas o al bloquear la pantalla;
  // el navegador solo deja salir de él (y de "suspended") dentro de un gesto.
  const c = bus.ctx;
  if (c && c.state !== "running" && c.state !== "closed") void c.resume().catch(() => {});
}

let gestureHooked = false;

/**
 * Desbloqueo global del audio: en CADA toque/clic/tecla se crea el contexto
 * si falta y se reanuda si quedó dormido. Sin esto, quien crea la sala online
 * toca "Crear sala", espera minutos a que alguien entre, la partida arranca
 * sola (sin ningún toque) y su contexto de audio sigue suspendido: juego en
 * silencio, mientras el otro jugador, que sí tocó "Unirse", oye todo.
 * Los listeners no se quitan: el audio puede volver a dormirse (pantalla
 * bloqueada, otra app) y el siguiente toque lo despierta.
 */
export function installAudioGestureUnlock(): () => void {
  if (typeof window === "undefined" || gestureHooked) return () => {};
  gestureHooked = true;
  const events = ["pointerdown", "touchstart", "touchend", "click", "keydown"] as const;
  const handler = () => {
    try {
      unlockAudio();
    } catch {
      /* sin audio */
    }
  };
  for (const e of events) window.addEventListener(e, handler, { capture: true, passive: true });
  return () => {
    for (const e of events) window.removeEventListener(e, handler, { capture: true });
    gestureHooked = false;
  };
}

function envGain(c: AudioContext, t: number, attack: number, dur: number, peak: number) {
  const g = c.createGain();
  g.gain.setValueAtTime(0.0001, t);
  g.gain.exponentialRampToValueAtTime(Math.max(0.001, peak), t + attack);
  g.gain.exponentialRampToValueAtTime(0.0001, t + dur);
  return g;
}

function tone(
  c: AudioContext,
  dest: AudioNode,
  type: OscillatorType,
  freq: number,
  t: number,
  dur: number,
  peak: number,
  slideTo?: number,
) {
  const o = c.createOscillator();
  o.type = type;
  o.frequency.setValueAtTime(freq, t);
  if (slideTo) o.frequency.exponentialRampToValueAtTime(Math.max(40, slideTo), t + dur);
  const g = envGain(c, t, 0.008, dur, peak);
  o.connect(g);
  g.connect(dest);
  o.start(t);
  o.stop(t + dur + 0.02);
}

// Los buffers de ruido se generaban muestra a muestra en el hilo principal
// con CADA golpe, aterrizaje y patada. Es ruido: reusar el mismo buffer
// suena igual y no cuesta nada. Se cachean por duración.
const noiseCache = new Map<number, AudioBuffer>();

function noiseBuffer(c: AudioContext, dur: number): AudioBuffer {
  const key = Math.round(dur * 1000);
  const hit = noiseCache.get(key);
  if (hit && hit.sampleRate === c.sampleRate) return hit;
  const n = Math.floor(c.sampleRate * dur);
  const buf = c.createBuffer(1, n, c.sampleRate);
  const d = buf.getChannelData(0);
  let last = 0;
  for (let i = 0; i < n; i++) {
    const white = Math.random() * 2 - 1;
    last = last * 0.82 + white * 0.18;
    d[i] = white * 0.6 + last;
  }
  noiseCache.set(key, buf);
  return buf;
}

function noise(c: AudioContext, dest: AudioNode, t: number, dur: number, peak: number, hp: number) {
  const src = c.createBufferSource();
  src.buffer = noiseBuffer(c, dur);
  const filter = c.createBiquadFilter();
  filter.type = "highpass";
  filter.frequency.value = hp;
  const g = envGain(c, t, 0.004, dur, peak);
  src.connect(filter);
  filter.connect(g);
  g.connect(dest);
  src.start(t);
  src.stop(t + dur + 0.02);
}

function startMusic(c: AudioContext, dest: AudioNode) {
  const bpm = 116;
  const beats = 8;
  const dur = (beats * 60) / bpm;
  const buf = c.createBuffer(1, Math.floor(c.sampleRate * dur), c.sampleRate);
  const d = buf.getChannelData(0);
  const sr = c.sampleRate;
  const beat = sr * (60 / bpm);
  const notes = [196, 247, 294, 247, 220, 294, 330, 247];
  const writeTone = (start: number, freq: number, len: number, amp: number, type: "sine" | "square") => {
    for (let i = 0; i < len && start + i < d.length; i++) {
      const k = i / len;
      const env = Math.sin(Math.min(1, k * 12) * Math.PI) * Math.exp(-k * 2.2);
      const wave =
        type === "sine"
          ? Math.sin((2 * Math.PI * freq * i) / sr)
          : Math.sign(Math.sin((2 * Math.PI * freq * i) / sr));
      d[start + i] += wave * env * amp;
    }
  };
  for (let b = 0; b < beats; b++) {
    const s = Math.floor(b * beat);
    writeTone(s, notes[b], Math.floor(beat * 0.7), 0.18, "sine");
    writeTone(s, notes[b] / 2, Math.floor(beat * 0.4), 0.14, "sine");
    if (b % 2 === 0) writeTone(s, 72, Math.floor(beat * 0.18), 0.28, "sine");
    if (b % 2 === 1) {
      for (let i = 0; i < beat * 0.12 && s + i < d.length; i++) {
        d[s + i] += (Math.random() * 2 - 1) * 0.08 * (1 - i / (beat * 0.12));
      }
    }
  }
  const src = c.createBufferSource();
  src.buffer = buf;
  src.loop = true;
  const g = c.createGain();
  g.gain.value = 0.9;
  src.connect(g);
  g.connect(dest);
  src.start();
  bus.musicSrc = src;
}

/**
 * Crowd roar with a stadium echo: the stands answer the goal. The roar
 * holds at full volume for the whole goal celebration (1.7 s, until the
 * ball is kicked off again from the centre) and the echo rings on top.
 */
let roarBuf: AudioBuffer | null = null;

function roarBuffer(c: AudioContext): AudioBuffer {
  if (roarBuf && roarBuf.sampleRate === c.sampleRate) return roarBuf;
  const n = Math.floor(c.sampleRate * 1.7);
  const buf = c.createBuffer(1, n, c.sampleRate);
  const d = buf.getChannelData(0);
  let last = 0;
  for (let i = 0; i < n; i++) {
    const white = Math.random() * 2 - 1;
    last = last * 0.86 + white * 0.14;
    d[i] = white * 0.35 + last;
  }
  roarBuf = buf;
  return buf;
}

function roar(c: AudioContext, dest: AudioNode, t: number) {
  const dur = 1.7;
  const src = c.createBufferSource();
  src.buffer = roarBuffer(c);
  const filter = c.createBiquadFilter();
  filter.type = "bandpass";
  filter.frequency.value = 900;
  filter.Q.value = 0.6;
  const g = c.createGain();
  g.gain.setValueAtTime(0.0001, t);
  g.gain.exponentialRampToValueAtTime(0.6, t + 0.12);
  g.gain.linearRampToValueAtTime(0.6, t + 1.2);
  g.gain.exponentialRampToValueAtTime(0.0001, t + dur);
  const delay = c.createDelay(1);
  delay.delayTime.value = 0.3;
  const feedback = c.createGain();
  feedback.gain.value = 0.4;
  const wet = c.createGain();
  wet.gain.value = 0.6;
  src.connect(filter);
  filter.connect(g);
  g.connect(dest);
  g.connect(delay);
  delay.connect(feedback);
  feedback.connect(delay);
  delay.connect(wet);
  wet.connect(dest);
  src.start(t);
  src.stop(t + dur + 0.02);
}

// ---- Tribuna dinámica: ambiente + intensidad por peligro ----
// La tribuna es un murmullo continuo que vive en el bus de efectos (el
// botón de silencio la cubre). Su nivel lo fija el componente cada
// fotograma según el peligro de la jugada; el gol es el pico.

/** Peligro de gol 0..1: el balón cerca de un arco, y más si vuela hacia él. */
export function crowdDanger(m: Match): number {
  const midY = (WORLD.goalTop + WORLD.goalBottom) / 2;
  const dl = Math.hypot(m.ball.x - WORLD.mouth, m.ball.y - midY);
  const dr = Math.hypot(m.ball.x - (WORLD.w - WORLD.mouth), m.ball.y - midY);
  const nearLeft = dl <= dr;
  const d = Math.min(dl, dr);
  let danger = Math.max(0, Math.min(1, 1 - d / 520));
  const toward = nearLeft ? m.ball.vx < 0 : m.ball.vx > 0;
  if (toward) {
    danger = Math.min(1, danger + Math.min(0.25, Math.hypot(m.ball.vx, m.ball.vy) / 4000));
  }
  return danger;
}

type CrowdNodes = {
  src: AudioBufferSourceNode;
  gain: GainNode;
  wet: GainNode;
  lastTarget: number;
};

const crowd: { nodes: CrowdNodes | null } = { nodes: null };

let crowdBuf: AudioBuffer | null = null;

function crowdBuffer(c: AudioContext) {
  if (crowdBuf && crowdBuf.sampleRate === c.sampleRate) return crowdBuf;
  // 3 s de ruido de grada en bucle: ruido suavizado, sin picos.
  const dur = 3;
  const n = Math.floor(c.sampleRate * dur);
  const buf = c.createBuffer(1, n, c.sampleRate);
  const d = buf.getChannelData(0);
  let last = 0;
  for (let i = 0; i < n; i++) {
    const white = Math.random() * 2 - 1;
    last = last * 0.9 + white * 0.1;
    d[i] = white * 0.25 + last;
  }
  // Fundido en los extremos para que el bucle no haga clic.
  const fade = Math.floor(c.sampleRate * 0.1);
  for (let i = 0; i < fade; i++) {
    const k = i / fade;
    d[i] *= k;
    d[n - 1 - i] *= k;
  }
  crowdBuf = buf;
  return buf;
}

/**
 * Generar los buffers pesados (roar de gol, tribuna, ruidos cortos) cuando
 * el navegador está ocioso, justo tras desbloquear el audio. Antes se
 * calculaban en el primer frame de partido y en el primer gol, y en un
 * celular eso eran 20-40 ms de tirón en esos instantes.
 */
function prewarmAudio(c: AudioContext) {
  const jobs: Array<() => void> = [
    () => void crowdBuffer(c),
    () => void roarBuffer(c),
    () => void noiseBuffer(c, 0.06),
    () => void noiseBuffer(c, 0.07),
    () => void noiseBuffer(c, 0.08),
    () => void noiseBuffer(c, 0.09),
    () => void noiseBuffer(c, 0.1),
  ];
  const idle =
    (typeof window !== "undefined" &&
      (window as unknown as { requestIdleCallback?: (cb: () => void) => void }).requestIdleCallback) ||
    ((cb: () => void) => setTimeout(cb, 60));
  const next = () => {
    const job = jobs.shift();
    if (!job) return;
    try {
      job();
    } catch {
      /* el audio es opcional */
    }
    idle(next);
  };
  idle(next);
}

function ensureCrowd(c: AudioContext) {
  if (crowd.nodes || !bus.sfx) return;
  const src = c.createBufferSource();
  src.buffer = crowdBuffer(c);
  src.loop = true;
  const filter = c.createBiquadFilter();
  filter.type = "bandpass";
  filter.frequency.value = 700;
  filter.Q.value = 0.5;
  const gain = c.createGain();
  gain.gain.value = 0.0001;
  // Eco bajito de estadio: el murmullo rebota suave.
  const delay = c.createDelay(1);
  delay.delayTime.value = 0.28;
  const feedback = c.createGain();
  feedback.gain.value = 0.25;
  const wet = c.createGain();
  wet.gain.value = 0.1;
  src.connect(filter);
  filter.connect(gain);
  gain.connect(bus.sfx);
  gain.connect(delay);
  delay.connect(feedback);
  feedback.connect(delay);
  delay.connect(wet);
  wet.connect(bus.sfx);
  src.start();
  crowd.nodes = { src, gain, wet, lastTarget: 0 };
}

/** Nivel de la tribuna 0..1: 0 = silencio, 1 = grada a tope. Suavizado. */
export function setCrowdLevel(level: number) {
  const c = bus.ctx;
  if (!c || !bus.sfx || c.state !== "running") return;
  ensureCrowd(c);
  const nodes = crowd.nodes;
  if (!nodes) return;
  const clamped = Math.max(0, Math.min(1, level));
  if (Math.abs(clamped - nodes.lastTarget) < 0.01) return;
  nodes.lastTarget = clamped;
  nodes.gain.gain.setTargetAtTime(clamped * 0.33, c.currentTime, 0.25);
  nodes.wet.gain.setTargetAtTime(0.1 + clamped * 0.4, c.currentTime, 0.25);
}

// El grito corto de gol estilo Miniclip ("¡Gol!", 0.7 s), por el bus de
// efectos para que el silencio lo cubra. Si falta el archivo, solo suena
// el rugido.
let golEl: HTMLAudioElement | null = null;
let golPan: StereoPannerNode | null = null;
let golFailed = false;

function playGolCall(pan: number) {
  const c = bus.ctx;
  if (!c || !bus.sfx || golFailed) return;
  if (!golEl || !golPan) {
    try {
      const el = new Audio("/gol.mp3");
      el.preload = "auto";
      el.addEventListener("error", () => {
        golFailed = true;
      });
      const src = c.createMediaElementSource(el);
      const panner = c.createStereoPanner();
      src.connect(panner);
      panner.connect(bus.sfx);
      golEl = el;
      golPan = panner;
    } catch {
      golFailed = true;
      return;
    }
  }
  golPan.pan.value = Math.max(-1, Math.min(1, pan));
  try {
    golEl.currentTime = 0;
    void golEl.play().catch(() => {
      golFailed = true;
    });
  } catch {
    golFailed = true;
  }
}

export function playSfx(id: SfxId, pan = 0, vol = 1) {
  const c = bus.ctx;
  const destBus = bus.sfx;
  if (!c || !destBus || c.state !== "running") return;
  const t = c.currentTime;
  const panner = c.createStereoPanner();
  panner.pan.value = Math.max(-1, Math.min(1, pan));
  panner.connect(destBus);
  const v = vol;
  const jitter = 0.96 + Math.random() * 0.08;

  switch (id) {
    case "jump":
      tone(c, panner, "square", 420 * jitter, t, 0.09, 0.08 * v, 680);
      break;
    case "doublejump":
      tone(c, panner, "triangle", 540 * jitter, t, 0.1, 0.1 * v, 900);
      tone(c, panner, "square", 720 * jitter, t + 0.045, 0.07, 0.06 * v, 980);
      break;
    case "land":
      noise(c, panner, t, 0.08, 0.18 * v, 120);
      tone(c, panner, "sine", 140, t, 0.09, 0.12 * v, 70);
      break;
    case "swish":
      noise(c, panner, t, 0.07, 0.1 * v, 900);
      break;
    case "kick":
      tone(c, panner, "sine", 180 * jitter, t, 0.12, 0.28 * v, 70);
      noise(c, panner, t, 0.06, 0.2 * v, 400);
      break;
    case "power":
      tone(c, panner, "sawtooth", 220 * jitter, t, 0.18, 0.16 * v, 90);
      tone(c, panner, "sine", 90, t, 0.2, 0.3 * v, 50);
      noise(c, panner, t, 0.1, 0.22 * v, 200);
      break;
    case "header":
      tone(c, panner, "triangle", 320 * jitter, t, 0.1, 0.16 * v, 180);
      break;
    case "hit":
      tone(c, panner, "sine", 110, t, 0.14, 0.3 * v, 50);
      noise(c, panner, t, 0.09, 0.22 * v, 180);
      break;
    case "bounce":
      tone(c, panner, "square", 280 * jitter, t, 0.06, 0.08 * v, 160);
      break;
    case "goal":
      roar(c, panner, t);
      playGolCall(pan);
      break;
    case "whistle":
      tone(c, panner, "sine", 1400, t, 0.18, 0.08 * v, 1800);
      tone(c, panner, "sine", 1800, t + 0.16, 0.22, 0.07 * v, 1500);
      break;
    case "sudden":
      tone(c, panner, "sawtooth", 330, t, 0.2, 0.1 * v, 660);
      tone(c, panner, "triangle", 495, t + 0.12, 0.3, 0.12 * v);
      break;
    case "stomp":
      noise(c, panner, t, 0.1, 0.16 * v, 150);
      tone(c, panner, "sine", 90, t, 0.12, 0.2 * v, 45);
      break;
    case "ui":
      tone(c, panner, "square", 660, t, 0.05, 0.06 * v);
      break;
    default:
      break;
  }
}
