s = open('new.html').read()
def rep(old, new, count=1):
    global s
    assert s.count(old) >= 1, "FALTA: " + old[:70]
    s = s.replace(old, new) if count == 0 else s.replace(old, new, count)

# ===== GAME FEEL: trauma-shake + hit-stop (Rafael 2026-10-30) =====
rep("function onCarHit(car) {",
    "function addTrauma(a){if(typeof S===\"undefined\"||!S)return;S.trauma=Math.min(1,(S.trauma||0)+a);}\n"
    "function updateTrauma(dt){if(typeof S===\"undefined\"||!S||!S.trauma)return;S.trauma=Math.max(0,S.trauma-dt*1.4);var sh=S.trauma*S.trauma;if(sh>0.002&&S.scene){var c=S.scene.cameras.main,m=sh*12;c.scrollX+=(Math.random()-0.5)*2*m;c.scrollY+=(Math.random()-0.5)*2*m;}}\n"
    "function hitStop(ms){if(typeof S===\"undefined\"||!S||!S.scene||S.hitStopOn)return;S.hitStopOn=true;try{S.scene.physics.pause();}catch(e){}setTimeout(function(){try{if(typeof S!==\"undefined\"&&S&&S.scene)S.scene.physics.resume();}catch(e){}try{if(typeof S!==\"undefined\"&&S)S.hitStopOn=false;}catch(e){}},ms);}\n"
    "function onCarHit(car) {")
rep("const FLOOD_Y0 = Math.ceil(arcHitY(FLOOD_X));", "const FLOOD_Y0 = Math.ceil(arcHitY(FLOOD_X));\nconst FLOOD_H = WORLD_H - FLOOD_Y0;")
rep("S.water = scene.add.tileSprite(FLOOD_X, 2060, 10, 3080, 'arroyo').setDepth(6);", "S.water = scene.add.tileSprite(FLOOD_X, (FLOOD_Y0 + WORLD_H) / 2, 10, FLOOD_H, 'arroyo').setDepth(6);")
rep("Phaser.Math.Between(560, WORLD_H), 'chev')", "Phaser.Math.Between(FLOOD_Y0 + 10, WORLD_H), 'chev')")
rep("S.water.setDisplaySize(46, 3080)", "S.water.setDisplaySize(46, FLOOD_H)")
rep("S.water.setDisplaySize(ROAD - 4, 3080)", "S.water.setDisplaySize(ROAD - 4, FLOOD_H)")
rep("y = Phaser.Math.Clamp(S.car.y + (Math.random() < 0.5 ? -1 : 1) * Phaser.Math.Between(650, 1150), 80, WORLD_H - 80);\n    if (Math.abs(y - S.car.y) < 500) return;",
    "y = Phaser.Math.Clamp(S.car.y + (Math.random() < 0.5 ? -1 : 1) * Phaser.Math.Between(420, 900), AV_TOP[ax] + 60, AV_BOT[ax] - 60);\n    if (Math.abs(y - S.car.y) < 320) return;")
rep("x = Phaser.Math.Clamp(S.car.x + (Math.random() < 0.5 ? -1 : 1) * Phaser.Math.Between(650, 1150), 80, RIVER_X0 - 120);\n    if (Math.abs(x - S.car.x) < 500) return;",
    "x = Phaser.Math.Clamp(S.car.x + (Math.random() < 0.5 ? -1 : 1) * Phaser.Math.Between(420, 900), ST_X0[sy] + 60, ST_X1[sy] - 60);\n    if (Math.abs(x - S.car.x) < 320) return;")
rep("roads.filter(sy => sy !== 1970 && sy !== 2790)", "roads.filter(sy => sy !== FLOODS.donjuan.y && sy !== FLOODS.leon.y)")
rep("> 1600) { deactivateTraffic(t); continue; }", "> 1100) { deactivateTraffic(t); continue; }")
rep("(fl === 'leon' && im.x > 2860)", "(fl === 'leon' && (im.x > FLOODS.leon.x1 - 80 || im.x < FLOODS.leon.x0 + 40))")
rep("if (im.x < 30 || im.x > RIVER_X0 - 30 || im.y < 30 || im.y > WORLD_H - 30) deactivateTraffic(t);", "if (!onRoad(im.x, im.y)) deactivateTraffic(t);")
rep("[2430 - 28, 1970 - 100, 0x90a4ae], [2430 + 28, 1970 - 195, 0xef5350],\n    [3350 + 28, 1970 + 100, 0x42a5f5], [3350 - 28, 1970 + 195, 0xffa726]",
    "[1705 - 28, 1400 - 90, 0x90a4ae], [1705 + 28, 1400 - 140, 0xef5350],\n    [2375 + 28, 1400 + 82, 0x42a5f5], [2375 - 28, 1400 + 138, 0xffa726]")
rep('<div id="carPicker">', '<div id="carPicker" style="display:none">')
rep("try { const savedCar = localStorage.getItem('arroyo_car'); if (savedCar && CAR_KEYS[savedCar]) CAR_CHOICE = savedCar; } catch (e) {}",
    "CAR_CHOICE = 'taxi'; // Sin selector (Rafael): el jugador siempre conduce el taxi")
rep("  g.fillStyle(0xffe082, 1); g.fillCircle(3, 3, 3);\n  g.fillStyle(0xffffff, 1); g.fillCircle(3, 3, 1.4);\n  g.generateTexture('spark', 6, 6); g.clear();",
    "  g.fillStyle(0xffe082, 1); g.fillCircle(3, 3, 3);\n  g.fillStyle(0xffffff, 1); g.fillCircle(3, 3, 1.4);\n  g.generateTexture('spark', 6, 6); g.clear();\n  // Bote de basura, poste de energía y luz de semáforo (props dinámicos)\n  g.fillStyle(0x546e7a, 1); g.fillRoundedRect(3, 5, 18, 20, 3);\n  g.fillStyle(0x37474f, 1); g.fillRoundedRect(1, 1, 22, 7, 3);\n  g.fillStyle(0x8bc34a, 1); g.fillRect(3, 12, 18, 4);\n  g.generateTexture('bin', 24, 28); g.clear();\n  g.fillStyle(0x000000, 0.22); g.fillEllipse(25, 27, 32, 10);\n  g.fillStyle(0x5d4037, 1); g.fillRect(6, 20, 38, 5);\n  g.fillStyle(0x3e2723, 1); g.fillCircle(25, 22, 7);\n  g.fillStyle(0x9e9e9e, 1); g.fillCircle(25, 22, 3);\n  g.generateTexture('pole', 50, 34); g.clear();\n  g.fillStyle(0xffffff, 0.35); g.fillCircle(8, 8, 8);\n  g.fillStyle(0xffffff, 1); g.fillCircle(8, 8, 5);\n  g.generateTexture('luz', 16, 16); g.clear();")
rep("  scene.textures.addBase64('carTaxi', CAR_SPRITES.taxi);\n  scene.textures.addBase64('carRojo', CAR_SPRITES.rojo);\n  scene.textures.addBase64('carAzul', CAR_SPRITES.azul);",
    "  scene.textures.addBase64('carTaxi', CAR_SPRITES.taxi);\n  scene.textures.addBase64('carRojo', CAR_SPRITES.rojo);\n  scene.textures.addBase64('carAzul', CAR_SPRITES.azul);\n  // Variantes del Spark para el tráfico: gris y negro (derivadas del azul al cargarse)\n  scene.textures.on('addtexture', key => {\n    if (key !== 'carAzul') return;\n    const src = scene.textures.get('carAzul').getSourceImage();\n    const mk = (name, f) => {\n      if (scene.textures.exists(name)) return;\n      const cv = document.createElement('canvas'); cv.width = src.width; cv.height = src.height;\n      const c2 = cv.getContext('2d'); c2.drawImage(src, 0, 0);\n      const id = c2.getImageData(0, 0, cv.width, cv.height), px = id.data;\n      for (let i = 0; i < px.length; i += 4) { const g0 = 0.3 * px[i] + 0.59 * px[i + 1] + 0.11 * px[i + 2]; const v = f(g0); px[i] = px[i + 1] = px[i + 2] = v; }\n      c2.putImageData(id, 0, 0);\n      scene.textures.addCanvas(name, cv);\n    };\n    mk('carGris', g0 => 95 + g0 * 0.5);\n    mk('carNegro', g0 => g0 * 0.3);\n  });")
rep("function trafficTint() {",
    "function pickTrafficTex() {\n  const keys = ['carAzul', 'carRojo', 'carNegro', 'carGris'].filter(k => S.scene.textures.exists(k));\n  return keys.length ? keys[Phaser.Math.Between(0, keys.length - 1)] : null;\n}\nfunction trafficTint() {")
rep("function setTrafficPose(t) {\n  const im = t.im;\n  if (t.dir === 0) { im.setTexture('car'); im.setAngle(0); im.body.setSize(40, 22); }\n  if (t.dir === 2) { im.setTexture('car'); im.setAngle(180); im.body.setSize(40, 22); }\n  if (t.dir === 1) { im.setTexture('carV'); im.setAngle(0); im.body.setSize(22, 40); }\n  if (t.dir === 3) { im.setTexture('carV'); im.setAngle(180); im.body.setSize(22, 40); }\n}",
    "function setTrafficPose(t) {\n  const im = t.im;\n  const key = t.tex || (t.tex = pickTrafficTex());\n  im.setScale(1); im.clearTint();\n  if (key) {\n    // Los demás carros usan el PNG del Spark (azul, rojo, negro o gris), como el del jugador\n    im.setTexture(key); im.setDisplaySize(54, 28);\n    if (t.dir === 0) { im.setAngle(0); im.body.setSize(168, 80); }\n    if (t.dir === 2) { im.setAngle(180); im.body.setSize(168, 80); }\n    if (t.dir === 1) { im.setAngle(90); im.body.setSize(80, 168); }\n    if (t.dir === 3) { im.setAngle(-90); im.body.setSize(80, 168); }\n    return;\n  }\n  if (t.dir === 0) { im.setTexture('car'); im.setAngle(0); im.body.setSize(40, 22); }\n  if (t.dir === 2) { im.setTexture('car'); im.setAngle(180); im.body.setSize(40, 22); }\n  if (t.dir === 1) { im.setTexture('carV'); im.setAngle(0); im.body.setSize(22, 40); }\n  if (t.dir === 3) { im.setTexture('carV'); im.setAngle(180); im.body.setSize(22, 40); }\n}")
rep("  setTrafficPose(slot);\n  im.setTint(trafficTint());",
    "  setTrafficPose(slot);\n  if (!slot.tex) im.setTint(trafficTint());")
rep("    if (aheadOf(S.car.x, S.car.y)) target = 0;\n    else {\n      for (const o of S.trafficPool) {\n        if (o.active && o !== t && aheadOf(o.im.x, o.im.y)) { target = 0; break; }\n      }\n    }\n    t.cur += Phaser.Math.Clamp(target - t.cur, -320 * dt, 150 * dt);",
    "    if (aheadOf(S.car.x, S.car.y)) target = 0;\n    else {\n      for (const o of S.trafficPool) {\n        if (o.active && o !== t && aheadOf(o.im.x, o.im.y)) { target = 0; break; }\n      }\n    }\n    // Semáforo: si el cruce siguiente tiene semáforo y no está en verde para su eje, frena\n    if (target > 0) {\n      if (t.dir === 0 || t.dir === 2) {\n        if (LIGHT_PHASE !== 'EW') {\n          let sy = null;\n          for (const s2 of ALL_STREETS) if (Math.abs(Math.abs(im.y - s2) - 28) < 9) { sy = s2; break; }\n          if (sy !== null) for (const ax of AVENUES) { const dd = (ax - im.x) * d.x; if (dd > 4 && dd < 120 && LIT.has(ax + ',' + sy)) { target = 0; break; } }\n        }\n      } else if (LIGHT_PHASE !== 'NS') {\n        let ax = null;\n        for (const a2 of AVENUES) if (Math.abs(Math.abs(im.x - a2) - 28) < 9) { ax = a2; break; }\n        if (ax !== null) for (const sy2 of ALL_STREETS) { const dd = (sy2 - im.y) * d.y; if (dd > 4 && dd < 120 && LIT.has(ax + ',' + sy2)) { target = 0; break; } }\n      }\n    }\n    t.cur += Phaser.Math.Clamp(target - t.cur, -320 * dt, 150 * dt);")
rep("  // Aviso de arrastre + ahogamiento del motor (si se apaga, el arroyo manda)",
    "  // Semáforos: fase global por reloj (ciclo de 16 s)\n  {\n    const cyc = (time / 1000) % 16;\n    const ph = cyc < 6.5 ? 'NS' : cyc < 8 ? 'Y1' : cyc < 14.5 ? 'EW' : 'Y2';\n    if (ph !== LIGHT_PHASE) { LIGHT_PHASE = ph; updateLightDots(); }\n  }\n  // Acera transitable: subirse desgasta el carro y saca chispas (ya no frena en seco)\n  if (S.started && !S.sweptBusy && Math.abs(fSpeed) > 55 && onSidewalk(car.x, car.y)) {\n    S.integrity = Math.max(0, S.integrity - 2.4 * dt);\n    if (time - (S.sidewalkAt || 0) > 110) { S.sidewalkAt = time; emitSparks(car.x, car.y + 8, 2); updateHUD(); }\n    if (S.integrity <= 0) tow('🔧 ¡El carro no aguantó los golpes!');\n  }\n  // Propiedad pública tumbable: tumbar un bote o un poste se resta del saldo (carrera limpia)\n  if (S.started && !S.sweptBusy && Math.abs(fSpeed) > 110) {\n    for (const p of PROPS) {\n      if (p.down) continue;\n      const dx = car.x - p.x, dy = car.y - p.y;\n      if (dx * dx + dy * dy < 784) {\n        p.down = true;\n        const fine = p.kind === 'poste' ? 25 : 10;\n        S.money = Math.max(0, S.money - fine);\n        emitSparks(p.x, p.y, 7);\n        S.scene.tweens.add({ targets: p.im, angle: p.im.angle + 82, x: p.x + dx * 0.7, y: p.y + dy * 0.7, duration: 260, ease: 'Quad.easeOut' });\n        p.im.setAlpha(0.85);\n        showAlert(p.kind === 'poste' ? '🚧 ¡Poste derribado! Daño a la propiedad pública: -$25' : '🗑️ ¡Bote de basura derribado! Multa: -$10', 2300);\n        updateHUD();\n      }\n    }\n  }\n  // Trancones recurrentes en puntos calientes de la ciudad\n  if (S.started && !S.sweptBusy) {\n    if (!S.jamAt) S.jamAt = time;\n    else if (time - S.jamAt > 80000) makeTrancon();\n  }\n  // Aviso de arrastre + ahogamiento del motor (si se apaga, el arroyo manda)")
rep("function makeTrancon() {\n  if (S.tranconDone) return;\n  S.tranconDone = true;\n  const spots = [\n    [1705 - 28, 1400 - 90, 0x90a4ae], [1705 + 28, 1400 - 140, 0xef5350],\n    [2375 + 28, 1400 + 82, 0x42a5f5], [2375 - 28, 1400 + 138, 0xffa726]\n  ];\n  spots.forEach(([x, y, tint]) => {\n    const sh = S.scene.add.image(x + 3, y + 5, 'blob');\n    sh.setAlpha(0.5); sh.setDepth(100 + y - 0.5); sh.setAngle(90);\n    const c = S.scene.physics.add.staticImage(x, y, 'carV');\n    c.setTint(tint); c.refreshBody(); c.setDepth(100 + y);\n    S.scene.physics.add.collider(S.car, c, onCarHit);\n  });\n  showAlert('🚗 ¡Trancón junto al arroyo Don Juan!', 2600);\n}",
    "function makeTrancon() {\n  // Trancón recurrente y reutilizable: 4 carros que se reubican en un punto caliente\n  S.jamAt = S.scene.time.now;\n  const sets = [\n    { name: 'un arroyo', cars: [[1677, 1310, 'V', 0], [1733, 1260, 'V', 0], [2403, 1482, 'V', 0], [2347, 1538, 'V', 0]] },\n    { name: 'Murillo con Olaya', cars: [[1830, 1562, 'H', 0], [1740, 1562, 'H', 0], [2130, 1618, 'H', 180], [2220, 1618, 'H', 180]] },\n    { name: 'un arroyo', cars: [[1600, 1752, 'H', 0], [1510, 1752, 'H', 0], [1810, 1808, 'H', 180]] }\n  ];\n  const set = sets[Phaser.Math.Between(0, sets.length - 1)];\n  if (!S.jamCars) {\n    S.jamCars = [];\n    for (let i = 0; i < 4; i++) {\n      const sh = S.scene.add.image(-300, -300, 'blob');\n      sh.setAlpha(0.5); sh.setVisible(false);\n      const c = S.scene.physics.add.staticImage(-300, -300, 'car');\n      c.setVisible(false);\n      S.scene.physics.add.collider(S.car, c, onCarHit);\n      S.jamCars.push({ im: c, sh });\n    }\n  }\n  S.jamCars.forEach((j, i) => {\n    const spot = set.cars[i];\n    if (!spot) { j.im.setPosition(-300, -300); j.im.refreshBody(); j.im.setVisible(false); j.sh.setVisible(false); return; }\n    const [x, y, kind, ang] = spot;\n    j.sh.setPosition(x + 3, y + 5); j.sh.setAngle(kind === 'V' ? 90 : 0); j.sh.setDepth(100 + y - 0.5); j.sh.setVisible(true);\n    const c = j.im;\n    const key = pickTrafficTex();\n    if (key) { c.setTexture(key); c.setDisplaySize(54, 28); c.setAngle(kind === 'V' ? 90 : ang); c.clearTint(); }\n    else if (kind === 'H') { c.setTexture('car'); c.setScale(1); c.setAngle(ang); c.setTint(trafficTint()); }\n    else { c.setTexture('carV'); c.setScale(1); c.setAngle(0); c.setTint(trafficTint()); }\n    c.setPosition(x, y); c.refreshBody(); if (key && kind === 'V') c.setBodySize(28, 54); else if (key) c.setBodySize(54, 28); c.setDepth(100 + y); c.setVisible(true);\n  });\n  showAlert('🚗 ¡Trancón en ' + set.name + '!', 2600);\n}")

rep("  const roofCols = [0xa15c48, 0x7d7d84, 0xb09a72, 0x5f7184];",
    "  const roofCols = [0xa15c48, 0x7d7d84, 0xb09a72, 0x5f7184, 0x00acc1, 0xff7043, 0xffca28, 0xec407a, 0x66bb6a, 0x7e57c2]; // +6 vivos (Barrio Abajo)")
rep("showAlert('⚠️ ¡AGUACERO! La 21, el Don Juan, el León y el Rebolo están desbordados', 3400)",
    "showAlert('⚠️ ¡AGUACERO! ¡Los arroyos están desbordados!', 3400)")


# ---------------- Efectos de sonido elegidos por Rafael ----------------
import base64 as _b64, os as _os
def _sfx64(name):
    with open(_os.path.expanduser('~/workspace/your_files/sfx-seleccion/game/' + name + '.mp3'), 'rb') as f:
        return 'data:audio/mpeg;base64,' + _b64.b64encode(f.read()).decode()

def _img64(ruta):
    import base64 as _b
    return 'data:image/png;base64,' + _b.b64encode(open(ruta, 'rb').read()).decode()

def _jpg64(ruta):
    import base64 as _b
    return 'data:image/jpeg;base64,' + _b.b64encode(open(ruta, 'rb').read()).decode()

def _webp64(ruta):
    import base64 as _b
    return 'data:image/webp;base64,' + _b.b64encode(open(ruta, 'rb').read()).decode()

SFX_BLOCK = (
  "// ===== Efectos de sonido (elegidos por Rafael; audios incrustados) =====\n"
  "const SFX_SRC = { ahogado: '" + _sfx64('ahogado') + "', taxi: '" + _sfx64('taxi') + "', silbido: '" + _sfx64('silbido') + "', salto: '" + _sfx64('salto') + "', cash: '" + _sfx64('cash') + "', motor: '" + _sfx64('motor') + "', busMotor: '" + _sfx64('bus-motor') + "', arranque: '" + _sfx64('arranque') + "', pito: '" + _sfx64('pito') + "', lluviaSuave: '" + _sfx64('lluvia-suave') + "', lluviaFuerte: '" + _sfx64('lluvia-fuerte') + "', trueno1: '" + _sfx64('trueno1') + "', trueno2: '" + _sfx64('trueno2') + "' };\n"
  "const SFX_EL = {};\n"
  "function sfxEl(n) { if (!SFX_EL[n]) { const a = new Audio(SFX_SRC[n]); a.preload = 'auto'; SFX_EL[n] = a; } return SFX_EL[n]; }\n"
  "function sfxPlay(n, vol) { try { const a = sfxEl(n); a.loop = false; a.currentTime = 0; a.volume = vol == null ? 0.9 : vol; const p = a.play(); if (p) p.catch(() => {}); } catch (e) {} }\n"
  "function sfxLoop(n, vol) { try { const a = sfxEl(n); a.loop = true; a.volume = vol == null ? 0.55 : vol; if (a.paused) { const p = a.play(); if (p) p.catch(() => {}); } } catch (e) {} }\n"
  "function sfxStop(n) { try { const a = SFX_EL[n]; if (a) { a.pause(); a.currentTime = 0; } } catch (e) {} }\n"
  "function rainAudio(p) { if (p === 1) { sfxStop('lluviaFuerte'); sfxLoop('lluviaSuave', 0.5); } else if (p >= 2) { sfxStop('lluviaSuave'); sfxLoop('lluviaFuerte', 0.6); } else { sfxStop('lluviaSuave'); sfxStop('lluviaFuerte'); } }\n"
)
rep("function startGame() {", SFX_BLOCK + "function startGame() {")
rep("  S.started = true;", "  S.started = true;\n  try { if (window.menuMusicStop) window.menuMusicStop(); } catch (e) {}\n  sfxPlay('arranque');\n  engineInit(); busEngineInit(); try { if (!S.radioOn) playRadio(0); } catch (e) {}\n  creaBarraContrib(); creaBotonPausa(); creaRadio();")
rep("function setPhase(p) {\n  const prev = S.phase;\n  S.phase = p;", "function setPhase(p) {\n  const prev = S.phase;\n  S.phase = p;\n  rainAudio(p);")
rep("      scene.cameras.main.shake(70, 0.0016);", "      scene.cameras.main.shake(70, 0.0016);\n      sfxPlay(Math.random() < 0.5 ? 'trueno1' : 'trueno2', Phaser.Math.FloatBetween(0.4, 0.8));")
rep("    if (aheadOf(S.car.x, S.car.y)) target = 0;", "    if (aheadOf(S.car.x, S.car.y)) { target = 0; if (!t.honkAt || S.scene.time.now > t.honkAt) { t.honkAt = S.scene.time.now + Phaser.Math.Between(5000, 11000); if (Math.random() < 0.55) sfxPlay('pito', Phaser.Math.Clamp(0.62 - Phaser.Math.Distance.Between(im.x, im.y, S.car.x, S.car.y) / 950, 0.16, 0.6)); } }")
rep("      showAlert('💦 ¡SE APAGÓ EL MOTOR! El arroyo te lleva…', 3000);", "      showAlert('💦 ¡SE APAGÓ EL MOTOR! El arroyo te lleva…', 3000);\n      sfxPlay('ahogado', 0.95);")



rep("// ===== Efectos de sonido (elegidos por Rafael; audios incrustados) =====",
    "// ===== Efectos de sonido (elegidos por Rafael; audios incrustados) =====\n"
    "// Motor sintetizado con Web Audio (AudioContext): responde continuo al acelerador\n"
    "let ENG = null;\n"
    "function engineInit() {\n"
    "  if (ENG) { if (ENG.ctx.state === 'suspended') ENG.ctx.resume(); return; }\n"
    "  try {\n"
    "    const Ctx = window.AudioContext || window.webkitAudioContext;\n"
    "    if (!Ctx) return;\n"
    "    const ctx = new Ctx();\n"
    "    const gain = ctx.createGain(); gain.gain.value = 0;\n"
    "    const filt = ctx.createBiquadFilter(); filt.type = 'lowpass'; filt.frequency.value = 500; filt.Q.value = 2;\n"
    "    const shaper = ctx.createWaveShaper();\n"
    "    const curve = new Float32Array(256);\n"
    "    for (let i = 0; i < 256; i++) { const x = i / 128 - 1; curve[i] = Math.tanh(2.2 * x); }\n"
    "    shaper.curve = curve;\n"
    "    const o1 = ctx.createOscillator(); o1.type = 'sawtooth'; o1.frequency.value = 68;\n"
    "    const o2 = ctx.createOscillator(); o2.type = 'square'; o2.frequency.value = 34;\n"
    "    const g2 = ctx.createGain(); g2.gain.value = 0.5;\n"
    "    const o3 = ctx.createOscillator(); o3.type = 'sawtooth'; o3.frequency.value = 68; o3.detune.value = 9;\n"
    "    const g3 = ctx.createGain(); g3.gain.value = 0.4;\n"
    "    o1.connect(shaper); o3.connect(g3); g3.connect(shaper); o2.connect(g2); g2.connect(shaper);\n"
    "    shaper.connect(filt); filt.connect(gain); gain.connect(ctx.destination);\n"
    "    o1.start(); o2.start(); o3.start();\n"
    "    ENG = { ctx, gain, filt, o1, o2, o3, rpm: 0.14, gasS: 0 };\n"
    "    document.addEventListener('visibilitychange', () => { if (!document.hidden && ENG && ENG.ctx.state === 'suspended') ENG.ctx.resume(); });\n"
    "  } catch (e) { ENG = null; }\n"
    "}\n"
    "function engineAudio() {\n"
    "  if (!S || !S.started) return;\n"
    "  if (typeof CAR_CHOICE !== 'undefined' && CAR_CHOICE === 'bus') { busEngineAudio(); return; }\n"
    "  if (S.busEl && !S.busEl.paused) { try { S.busEl.pause(); S.busEl.volume = 0; } catch (e) {} }\n"
    "  if (!ENG) return;\n"
    "  const t = ENG.ctx.currentTime;\n"
    "  if (S.stalled) { ENG.gain.gain.setTargetAtTime(0, t, 0.06); return; }\n"
    "  const gas = (S.cursors && S.cursors.up.isDown) || (S.keys && S.keys.up.isDown) || (S.touch && S.touch.gas) ? 1 : 0;\n"
    "  ENG.gasS += (gas - ENG.gasS) * 0.10;\n"
    "  const ratio = Math.min(1, (S.car ? S.car.body.speed : 0) / 430);\n"
    "  let rpm = 0.14 + ENG.gasS * 0.52 + ratio * 0.34;\n"
    "  if (rpm > 1) rpm = 1;\n"
    "  ENG.rpm += (rpm - ENG.rpm) * 0.12;\n"
    "  let f = 36 + ENG.rpm * 96;\n"
    "  let fvol = 0.16 + ENG.gasS * 0.26 + ratio * 0.12;\n"
    "  let ffilt = 260 + ENG.rpm * 620 + ENG.gasS * 160;\n"
    "  const fl2 = (S.car && S.phase >= 2) ? floodKeyAt(S.car.x, S.car.y, S.phase) : null;\n"
    "  if (fl2) { f *= 0.60; ffilt *= 0.55; fvol *= 0.82; if (Math.sin(t * 43) > 0.78) f *= 0.55; if (Math.sin(t * 29) > 0.9) f *= 0.7; }\n"
    "  ENG.o1.frequency.setTargetAtTime(f, t, 0.05);\n"
    "  ENG.o3.frequency.setTargetAtTime(f, t, 0.05);\n"
    "  ENG.o2.frequency.setTargetAtTime(f / 2, t, 0.05);\n"
    "  ENG.filt.frequency.setTargetAtTime(ffilt, t, 0.08);\n"
    "  ENG.gain.gain.setTargetAtTime(fvol, t, 0.09);\n"
    "}\n")
rep("    else if (time - S.jamAt > 80000) makeTrancon();",
    "    else if (time - S.jamAt > 80000) makeTrancon();\n    engineAudio();\n    mecanicaObjetivo(time, dt);")

# ================= OBJETIVO DEL JUEGO: canalizar los arroyos =================
rep("  const fl = S.phase > 0 ? floodKeyAt(car.x, car.y, S.phase) : null;",
    "  const fl = (S.airT > 0) ? null : (S.phase > 0 ? floodKeyAt(car.x, car.y, S.phase) : null);\n"
    "  if (fl && S.phase === 3 && RIVER_FLOW.includes(fl) && car.x > RIVER_X0 - 60 && !S.sweptBusy) riverLoss();")
rep("(fl === 'donjuan' && im.x > RIVER_X0 - 70)", "(RIVER_FLOW.includes(fl) && im.x > RIVER_X0 - 70)")
rep("    if (S.phase >= 2) roads = roads.filter(sy => sy !== FLOODS.donjuan.y && sy !== FLOODS.leon.y);",
    "    if (S.phase >= 2) roads = roads.filter(sy => !Object.values(FLOODS).some(f => f.kind === 'h' && f.y === sy));")
rep("  if (S.trafficAt <= 0 && activeCount < 12) { S.trafficAt = 1.4; spawnTraffic(); }",
    "  const enPico = S.rushUntil && S.scene.time.now < S.rushUntil;\n"
    "  if (S.trafficAt <= 0 && activeCount < (enPico ? 14 : 12)) { S.trafficAt = enPico ? 0.5 : 1.4; spawnTraffic(); }")
rep("  let fare = Math.round(50 + S.mission.timeLeft * 2);\n  let note = '';\n  if (S.phase === 2) { fare = Math.round(fare * 1.5); note = ' 🌧️ ¡Tarifa de aguacero!'; }",
    "  let fare = Math.round(50 + S.mission.timeLeft * 2);\n  let note = '';\n  if (S.phase === 2) { fare = Math.round(fare * 1.5); note = ' 🌧️ ¡Tarifa de aguacero!'; }\n"
    "  if (S.mission.desperate) { fare = Math.round(fare * 1.6); note += ' 😰 ¡Desesperado!'; }\n"
    "  if (S.mission.rampBonus) { fare *= 2; note += ' 🪂 ¡Doble por el salto!'; }\n"
    "  note += ' 🏗️ Impuestos: $' + Math.round(fare * 0.3);")
rep("  S.money += fare; S.services++;",
    "  const impT = Math.round(fare * 0.3); S.contrib = (S.contrib || 0) + impT; led().servicios += fare; led().impuestos += impT; S.money += fare - impT; S.services++; sfxPlay('cash', 0.8);")
rep("    S.mission = { stage: 'pickup', spot };",
    "    S.mission = { stage: 'pickup', spot };\n"
    "    if (Math.random() < 0.3) { S.mission.desperate = true; S.person.setTint(0xff5252); showAlert('😰 ¡Pasajero desesperado! Paga 60% más, pero su tiempo es corto', 2600); } else S.person.clearTint();")
rep("  const total = Math.round(38 + dist / 30);",
    "  let total = Math.round(38 + dist / 30); if (S.mission && S.mission.desperate) total = Math.round(total * 0.55);")
rep("  S.mission = { stage: 'dropoff', spot: dest, timeLeft: total, timeTotal: total };",
    "  S.mission = { stage: 'dropoff', spot: dest, timeLeft: total, timeTotal: total, desperate: !!(S.mission && S.mission.desperate), rampBonus: false };")
rep("function cancelService() {\n  S.mission = null;",
    "function cancelService() {\n  const stg = S.mission ? S.mission.stage : '';\n  S.mission = null;")
rep("  showAlert('😤 ¡El pasajero se cansó de esperar!', 2400);",
    "  showAlert(stg === 'dropoff' ? '😤 ¡El pasajero se bajó sin pagar!' : '😤 ¡El pasajero se cansó de esperar!', 2400);")
rep("  S.money -= cost;", "  S.money -= cost; led().gruas += cost;")
rep("        S.money = Math.max(0, S.money - fine);", "        S.money = Math.max(0, S.money - fine); led().multas += fine;")
rep("// ===== Efectos de sonido (elegidos por Rafael; audios incrustados) =====",
    "// ===== Efectos de sonido (elegidos por Rafael; audios incrustados) =====\n"
    "// ===== Objetivo: canalizar los arroyos con los impuestos (modo libre) =====\n"
    "// ===== MENÚ DE PAUSA Y ESTADÍSTICAS =====\n"
    "function fmtTimePausa(sec) { const m = Math.floor(sec / 60), s = Math.floor(sec % 60); return m + ':' + (s < 10 ? '0' : '') + s; }\n"
        "function creaBotonPausa() {\n"
    "  if (document.getElementById('btnPausa')) return;\n"
    "  const st = document.createElement('style');\n"
    "  st.textContent = '#btnPausa{position:fixed;left:10px;top:8px;z-index:67;width:42px;height:42px;border-radius:50%;background:rgba(15,23,32,.85);color:#fff;border:1px solid rgba(255,255,255,.4);font:700 18px Nunito,Arial,sans-serif;cursor:pointer} #pausaBack{position:fixed;inset:0;z-index:94;background:rgba(6,10,14,.45);display:none} #pausaBack.open{display:block} #pausaPanel{position:fixed;left:0;top:0;height:100%;width:min(84vw,320px);z-index:95;transform:translateX(-106%);transition:transform .28s ease;background:#101820;color:#eef4f8;border-right:1px solid rgba(255,255,255,.16);font-family:Nunito,Arial,sans-serif;box-shadow:4px 0 18px rgba(0,0,0,.4)} #pausaPanel.open{transform:translateX(0)} #pausaCard{padding:18px;max-height:100%;overflow:auto;box-sizing:border-box} #pausaCard h2{margin:0 0 8px;font-size:20px} #pausaCard table{width:100%;border-collapse:collapse;font-size:14px} #pausaCard td{padding:5px 4px;border-bottom:1px solid rgba(255,255,255,.08)} #pausaCard .n{text-align:right;font-weight:700;white-space:nowrap} .pbtnRow{display:flex;gap:8px;margin-top:14px;flex-wrap:wrap} .pbtnGo{flex:1;border:0;border-radius:10px;padding:11px;font:800 14px Nunito,Arial,sans-serif;cursor:pointer;color:#fff;background:#2e7d32} .pbtnTaller{flex:1;border:0;border-radius:10px;padding:11px;font:800 14px Nunito,Arial,sans-serif;cursor:pointer;color:#fff;background:#1565c0} .pbtnMenu{flex:1;border:0;border-radius:10px;padding:11px;font:800 14px Nunito,Arial,sans-serif;cursor:pointer;color:#14202b;background:#ffd54f} .pbtnSalir{flex:1;border:0;border-radius:10px;padding:11px;font:800 14px Nunito,Arial,sans-serif;cursor:pointer;color:#fff;background:#e11d2e} .pbtnEst{flex:1;border:0;border-radius:10px;padding:11px;font:800 14px Nunito,Arial,sans-serif;cursor:pointer;color:#14202b;background:#ffd54f} @media (orientation:portrait){#btnPausa{top:12px;left:12px}}';\n"
    "  document.head.appendChild(st);\n"
    "  const b = document.createElement('button');\n"
    "  b.id = 'btnPausa';\n"
    "  b.textContent = '☰';\n"
    "  b.onclick = () => openPausa();\n"
    "  document.body.appendChild(b);\n"
    "}\n"
    "function estadisticasHTML() {\n"
    "  const L = led();\n"
    "  const ded = L.gruas + L.danos + L.multas + L.impuestos;\n"
    "  const bal = L.servicios + L.saltos - ded;\n"
    "  return '<h2 style=margin-top:16px>📊 ESTADÍSTICAS</h2><table>'\n"
    "    + '<tr><td>🚕 Servicios completados</td><td class=n>' + (S.services || 0) + '</td></tr>'\n"
    "    + '<tr><td>🕒 Tiempo jugado</td><td class=n>' + fmtTimePausa(S.playTime || 0) + '</td></tr>'\n"
    "    + '<tr><td>💵 Ingresos por servicios</td><td class=n>+$' + L.servicios + '</td></tr>'\n"
    "    + '<tr><td>🪂 Bonos por saltos</td><td class=n>+$' + L.saltos + '</td></tr>'\n"
    "    + '<tr><td>➖ Deducciones</td><td class=n>−$' + ded + '</td></tr>'\n"
    "    + '<tr><td><b>Balance</b></td><td class=n><b>' + (bal >= 0 ? '+$' : '−$') + Math.abs(bal) + '</b></td></tr>'\n"
    "    + '<tr><td>🏗️ Fondo de canalización</td><td class=n>$' + Math.floor(S.contrib || 0) + ' / $' + contribGoal() + '</td></tr>'\n"
    "    + '<tr><td>🌊 Arroyos eliminados</td><td class=n>' + ELIM.size + ' de ' + Object.keys(FLOODS).length + '</td></tr>'\n"
    "    + '</table>';\n"
    "}\n"
    "function statsHTMLPausa() {\n"
    "  return (function(){ var t = S.misionActiva ? 'ABANDONAR MISIÓN' : S.carreraActiva ? 'ABANDONAR CARRERA' : S.multiActiva ? 'ABANDONAR PARTIDA' : ''; return t ? '<button class=pbtnSalir style=width:100%;margin-bottom:10px onclick=abandonarPartida()>' + t + '</button>' : ''; })()\n"
    "    + misionesHTMLPausa()\n"
    "    + '<div class=pbtnRow><button class=pbtnGo onclick=closePausa()>▶ SEGUIR JUGANDO</button><button class=pbtnEst onclick=abrirEstadisticasDesdePausa()>📊 ESTADÍSTICAS</button><button class=pbtnMenu onclick=irAMenuDesdePausa()>Menú principal</button><button class=pbtnSalir onclick=salirDelJuegoDesdePausa()>Salir del juego</button></div>';\n"
    "}\n"
    "function abrirEstadisticasDesdePausa() {\n"
    "  const p = document.getElementById('pausaPanel');\n"
    "  if (p) p.classList.remove('open');\n"
    "  const bk0 = document.getElementById('pausaBack');\n"
    "  if (bk0) bk0.classList.remove('open');\n"
    "  let bk = document.getElementById('estadisticasBack');\n"
    "  if (!bk) {\n"
    "    bk = document.createElement('div'); bk.id = 'estadisticasBack'; bk.onclick = () => cerrarEstadisticas(); document.body.appendChild(bk);\n"
    "    const q = document.createElement('div'); q.id = 'estadisticasPanel'; q.innerHTML = '<div id=estadisticasCard></div>'; document.body.appendChild(q);\n"
    "    const st = document.createElement('style');\n"
    "    st.textContent = '#estadisticasBack{position:fixed;inset:0;z-index:96;background:rgba(6,10,14,.55);display:none} #estadisticasBack.open{display:block} #estadisticasPanel{position:fixed;left:50%;top:50%;transform:translate(-50%,-50%);width:min(88vw,360px);max-height:92vh;overflow:auto;z-index:97;background:#101820;color:#eef4f8;border:1px solid rgba(255,255,255,.2);border-radius:16px;box-shadow:0 8px 30px rgba(0,0,0,.5);font-family:Nunito,Arial,sans-serif;padding:20px;box-sizing:border-box;display:none} #estadisticasPanel.open{display:block} #estadisticasPanel table{width:100%;border-collapse:collapse;font-size:14px} #estadisticasPanel td{padding:5px 4px;border-bottom:1px solid rgba(255,255,255,.08)} #estadisticasPanel .n{text-align:right;font-weight:700;white-space:nowrap}';\n"
    "    document.head.appendChild(st);\n"
    "  }\n"
    "  document.getElementById('estadisticasCard').innerHTML = estadisticasHTML() + '<button class=pbtnGo style=width:100%;margin-top:14px onclick=cerrarEstadisticas()>← VOLVER A MISIONES</button>';\n"
    "  bk.classList.add('open');\n"
    "  document.getElementById('estadisticasPanel').classList.add('open');\n"
    "}\n"
    "function cerrarEstadisticas() {\n"
    "  const q = document.getElementById('estadisticasPanel');\n"
    "  if (q) q.classList.remove('open');\n"
    "  const bk = document.getElementById('estadisticasBack');\n"
    "  if (bk) bk.classList.remove('open');\n"
    "  openPausa();\n"
    "}\n"
    "function openPausa() {\n"
    "  if (!S.started) return;\n"
    "  let p = document.getElementById('pausaPanel');\n"
    "  if (!p) {\n"
    "    p = document.createElement('div'); p.id = 'pausaPanel'; p.innerHTML = '<div id=pausaCard></div>'; document.body.appendChild(p);\n"
    "    const bk = document.createElement('div'); bk.id = 'pausaBack'; bk.onclick = () => closePausa(); document.body.appendChild(bk);\n"
    "  }\n"
    "  document.getElementById('pausaCard').innerHTML = statsHTMLPausa();\n"
    "  p.classList.add('open');\n"
    "  document.getElementById('pausaBack').classList.add('open');\n"
    "  S.scene.scene.pause();\n"
    "  engineMute();\n"
    "  radioDuck();\n"
    "}\n"
    "function closePausa() {\n"
    "  const p = document.getElementById('pausaPanel');\n"
    "  if (p) p.classList.remove('open');\n"
    "  const bk = document.getElementById('pausaBack');\n"
    "  if (bk) bk.classList.remove('open');\n"
    "  if (S.scene) S.scene.scene.resume();\n"
    "  radioUnduck();\n"
    "}\n"
    "function irAlTallerDesdePausa() {\n"
    "  openPausa();\n"
    "}\n"
    "function irAMultiDesdePausa() {\n"
    "  const p = document.getElementById('pausaPanel');\n"
    "  if (p) p.classList.remove('open');\n"
    "  const bk = document.getElementById('pausaBack');\n"
    "  if (bk) bk.classList.remove('open');\n"
    "  const ov = document.getElementById('startOverlay');\n"
    "  if (ov) ov.style.display = '';\n"
    "  try { if (typeof cancelarCarrera === 'function') cancelarCarrera(); } catch (e) {}\n"
    "  try { if (typeof cancelarMulti === 'function') cancelarMulti(); } catch (e) {}\n"
    "  if (typeof killaUIShow === 'function') killaUIShow('multi');\n"
    "  try { stopRadio(); } catch (e) {}\n"
    "}\n"
    "function irAMenuDesdePausa() {\n"
    "  const p = document.getElementById('pausaPanel');\n"
    "  if (p) p.classList.remove('open');\n"
    "  const bk = document.getElementById('pausaBack');\n"
    "  if (bk) bk.classList.remove('open');\n"
    "  try { if (typeof cancelarCarrera === 'function') cancelarCarrera(); } catch (e) {}\n"
    "  try { if (typeof cancelarMulti === 'function') cancelarMulti(); } catch (e) {}\n"
    "  try { stopRadio(); } catch (e) {}\n"
    "  try { if (typeof ENG !== 'undefined' && ENG && ENG.gain && ENG.ctx) ENG.gain.gain.setTargetAtTime(0, ENG.ctx.currentTime, 0.05); } catch (e) {}\n"
    "  try { if (S && S.busEl && !S.busEl.paused) { S.busEl.pause(); S.busEl.volume = 0; } } catch (e) {}\n"
    "  try { if (typeof SFX_EL !== 'undefined') for (var _mk in SFX_EL) { try { var _ma = SFX_EL[_mk]; if (_ma) { _ma.pause(); _ma.currentTime = 0; } } catch (e2) {} } } catch (e) {}\n"
    "  try { if (typeof rainAudio === 'function') rainAudio(0); } catch (e) {}\n"
    "  try { if (S) S.started = false; } catch (e) {}\n"
    "  const ov = document.getElementById('startOverlay');\n"
    "  if (ov) ov.style.display = '';\n"
    "  if (typeof killaUIShow === 'function') killaUIShow('modo');\n"
    "  try { if (window.menuMusicStart) window.menuMusicStart(); } catch (e) {}\n"
    "}\n"
    "function abandonarPartida() {\n"
    "  if (typeof window.killaBackConfirm === 'function') window.killaBackConfirm();\n"
    "  else { try { closePausa(); } catch (e) {} if (typeof killaUIShow === 'function') killaUIShow('modo'); }\n"
    "}\n"
    "function salirDelJuegoDesdePausa() {\n"
    "  const p = document.getElementById('pausaPanel');\n"
    "  if (p) p.classList.remove('open');\n"
    "  const bk = document.getElementById('pausaBack');\n"
    "  if (bk) bk.classList.remove('open');\n"
    "  try { if (typeof cancelarCarrera === 'function') cancelarCarrera(); } catch (e) {}\n"
    "  try { if (typeof cancelarMulti === 'function') cancelarMulti(); } catch (e) {}\n"
    "  try { stopRadio(); } catch (e) {}\n"
    "  try { window.close(); } catch (e) {}\n"
    "  const ov = document.getElementById('startOverlay');\n"
    "  if (ov) ov.style.display = '';\n"
    "  if (typeof killaUIShow === 'function') killaUIShow('portada');\n"
    "}\n"
    "document.addEventListener('keydown', (e) => {\n"
    "  if (!S || !S.started) return;\n"
    "  if (e.code === 'Escape' || e.code === 'KeyP') {\n"
        "    const p = document.getElementById('pausaPanel');\n"
    "    if (p && p.classList.contains('open')) closePausa(); else openPausa();\n"
    "  }\n"
    "});\n"
    "document.addEventListener('visibilitychange', () => { if (document.hidden && S && S.started) openPausa(); });\n"
        "// ===== RADIO ONLINE (barra superior: anterior / nombre / siguiente / volumen) =====\n"
    "const RADIOS = [\n"
    "  { n: '⭐ INNOVACION STEREO', s: 'Innovacion Stereo', ic: 'innovacion', u: 'https://stream-034.zeno.fm/9r21a1mp3a0uv', f: 'https://stream-034.zeno.fm/9r21a1mp3a0uv?zs=LWReFH24TRCtfJ_NOj-6jg' },\n"
    "  { n: '🌴 TROPICAL · SALSA', s: 'ZonaSalsa', ic: 'zonasalsa', u: 'https://cast6.asurahosting.com/proxy/salsafou/stream', f: 'https://us-b4-p-e-qg12-audio.cdn.mdstrm.com/live-audio-aw/632c9d30aa9ace684913b853' },\n"
    "  { n: '🎧 URBANA · BARRANQUILLA', s: 'Mix 103.9', ic: 'mix', u: 'https://playerservices.streamtheworld.com/api/livestream-redirect/MIX_BARRANQUILLA.mp3', f: 'https://24283.live.streamtheworld.com/MIX_BARRANQUILLA.mp3' },\n"
    "  { n: '🎸 ROCK', s: 'Radioacktiva', ic: 'radioacktiva', u: 'https://playerservices.streamtheworld.com/api/livestream-redirect/RADIO_ACTIVAAAC.aac', f: 'https://playerservices.streamtheworld.com/api/livestream-redirect/RADIOACKTIVA_MEDAAC.aac' }\n"
    "];\n"
    "let radioIdx = -1;\n"
    "function creaRadio() {\n"
    "  if (document.getElementById('radioBar')) return;\n"
    "  const st = document.createElement('style');\n"
    "  st.textContent = '#radioBar{position:fixed;left:50%;transform:translateX(-50%);bottom:12px;z-index:66;display:flex;align-items:center;gap:7px;background:rgba(15,23,32,.85);border:1px solid rgba(255,255,255,.3);border-radius:999px;padding:5px 10px;font-family:Nunito,Arial,sans-serif} @media (orientation:portrait){#radioBar{bottom:160px}} .rnav{background:#1c2836;color:#fff;border:1px solid rgba(255,255,255,.25);border-radius:50%;width:30px;height:30px;font-size:13px;cursor:pointer;flex:none} #radioIcon{width:26px;height:26px;object-fit:contain;border-radius:6px;display:none}#radioName{color:#fff;font:700 12px Nunito,Arial,sans-serif;text-align:center;cursor:pointer;white-space:nowrap} #radioVol{width:72px;accent-color:#2e7d32}';\n"
    "  document.head.appendChild(st);\n"
    "  const bar = document.createElement('div');\n"
    "  bar.id = 'radioBar';\n"
    "  bar.innerHTML = '<button class=rnav onclick=radioNav(-1)>◀</button><input id=radioVol type=range min=0 max=100 value=80 oninput=radioVol(this.value)><div class=raLcd><div id=radioName onclick=radioToggle()>RADIO</div><div class=raFm>FM · STEREO</div></div><button class=\"rnav flip\" onclick=radioNav(1)>◀</button>';\n"

    "  document.body.appendChild(bar);\n"
    "  if (S.radioOn && RADIOS[radioIdx]) { const rr = RADIOS[radioIdx]; const nm2 = document.getElementById('radioName'); if (nm2) { nm2.textContent = rr.s; try { radioFitName(); } catch (e) {} } const ic2 = document.getElementById('radioIcon'); if (ic2 && rr.ic && RADIO_ICONS[rr.ic]) { ic2.src = RADIO_ICONS[rr.ic]; ic2.style.display = 'block'; } }\n"
    "}\n"
    "function radioToggle() { if (radioIdx < 0) playRadio(0); else stopRadio(); }\n"
    "function radioNav(d) { let i = radioIdx + d; if (i < 0) i = RADIOS.length - 1; if (i >= RADIOS.length) i = 0; playRadio(i); }\n"
    "function radioVol(v) { if (S.radioEl) { if (S.radioDucked) { S.radioVolBase = v / 100; S.radioEl.volume = Math.min(v / 100, 0.15); } else S.radioEl.volume = v / 100; } }\n"
    "function radioDuck() { try { if (!S.radioEl || !S.radioOn || S.radioDucked) return; S.radioDucked = true; S.radioVolBase = S.radioEl.volume; S.radioEl.volume = Math.min(S.radioEl.volume, 0.15); } catch (e) {} }\n"
    "function radioUnduck() { try { if (!S.radioDucked) return; S.radioDucked = false; if (S.radioEl) { const v = document.getElementById('radioVol'); S.radioEl.volume = v ? v.value / 100 : (S.radioVolBase != null ? S.radioVolBase : 0.8); } } catch (e) {} }\n"
    "function playRadio(i) {\n"
    "  const r = RADIOS[i];\n"
    "  radioIdx = i;\n"
    "  S.radioOn = true;\n"
    "  if (!S.radioEl) { S.radioEl = new Audio(); S.radioEl.preload = 'none'; }\n"
    "  const el = S.radioEl;\n"
    "  el.onerror = () => { if (el.dataset.fb !== '1' && r.f) { el.dataset.fb = '1'; el.src = r.f; el.play().catch(() => {}); } else showAlert('📻 ' + r.s + ' no respondió — prueba otra', 2600); };\n"
    "  el.dataset.fb = '';\n"
    "  el.src = r.u;\n"
    "  const vol = document.getElementById('radioVol');\n"
    "  el.volume = vol ? vol.value / 100 : 0.8;\n"
    "  if (S.radioDucked) el.volume = Math.min(el.volume, 0.15);\n"
    "  el.play().catch(() => {});\n"
    "  const nm = document.getElementById('radioName');\n"
    "  if (nm) { nm.textContent = r.s; try { radioFitName(); } catch (e) {} }\n"
    "  const ic = document.getElementById('radioIcon'); if (ic) { if (r.ic && RADIO_ICONS[r.ic]) { ic.src = RADIO_ICONS[r.ic]; ic.style.display = 'block'; } else ic.style.display = 'none'; }\n"
    "  showAlert('📻 ' + r.n + ' — ' + r.s, 2000);\n"
    "}\n"
    "// Ajusta el nombre de la emisora al display LCD (Rafael 2026-10-30):\n"
    "function radioFitName() {\n"
    "  var nm = document.getElementById('radioName');\n"
    "  if (!nm) return;\n"
    "  var len = (nm.textContent || '').length;\n"
    "  var fs = 13;\n"
    "  if (len > 12) fs = 11;\n"
    "  if (len > 15) fs = 10;\n"
    "  nm.style.setProperty('font-size', fs + 'px', 'important');\n"
    "}\n"
    "function stopRadio() {\n"
    "  if (S.radioEl) { S.radioEl.pause(); S.radioEl.removeAttribute('src'); S.radioEl.load(); }\n"
    "  radioIdx = -1;\n"
    "  S.radioOn = false;\n"
    "  S.radioDucked = false;\n"
    "  const nm = document.getElementById('radioName');\n"
    "  if (nm) { nm.textContent = 'RADIO'; try { radioFitName(); } catch (e) {} }\n"
    "  const ic = document.getElementById('radioIcon'); if (ic) ic.style.display = 'none';\n"
    "}\n"
    "// ===== MOTOR REAL (muestra en bucle: Honda CRV, Freesound CC0) =====\n"
    "function engineInitR() {\n"
    "  if (S.engEl) { if (S.engEl.paused) { const pr = S.engEl.play(); if (pr) pr.catch(() => {}); } return; }\n"
    "  try {\n"
    "    const a = sfxEl('motor');\n"
    "    a.loop = true;\n"
    "    a.volume = 0;\n"
    "    S.engEl = a;\n"
    "    const pr = a.play();\n"
    "    if (pr) pr.catch(() => {});\n"
    "    document.addEventListener('visibilitychange', () => { if (!document.hidden && S.engEl && S.engEl.paused && S.started && !S.stalled) { const q = S.engEl.play(); if (q) q.catch(() => {}); } });\n"
    "  } catch (e) {}\n"
    "}\n"
    "function engineMute() { if (S.busEl) { try { S.busEl.volume = 0.03; } catch (e) {} } if (S.engEl) { try { S.engEl.volume = 0.03; } catch (e) {} } if (typeof ENG !== 'undefined' && ENG.gain && ENG.ctx) { try { ENG.gain.gain.setTargetAtTime(0.02, ENG.ctx.currentTime, 0.05); } catch (e) {} } }\n"
    "function engineAudioR() {\n"
    "  const a = S.engEl;\n"
    "  if (!a || !S || !S.started) return;\n"
    "  if (!ENG) ENG = { rpm: 0.14, gasS: 0 };\n"
    "  if (S.stalled) { a.volume = Math.max(0, a.volume - 0.1); return; }\n"
    "  const gas = (S.cursors && S.cursors.up.isDown) || (S.keys && S.keys.up.isDown) || (S.touch && S.touch.gas) ? 1 : 0;\n"
    "  ENG.gasS += (gas - ENG.gasS) * 0.10;\n"
    "  const ratio = Math.min(1, (S.car ? S.car.body.speed : 0) / 430);\n"
    "  let rpm = 0.14 + ENG.gasS * 0.52 + ratio * 0.34;\n"
    "  if (rpm > 1) rpm = 1;\n"
    "  ENG.rpm += (rpm - ENG.rpm) * 0.12;\n"
    "  let rate = 0.84 + ENG.rpm * 0.76;\n"
    "  let vol = 0.36 + ENG.gasS * 0.30 + ratio * 0.20;\n"
    "  const fl2 = (S.car && S.phase >= 2) ? floodKeyAt(S.car.x, S.car.y, S.phase) : null;\n"
    "  if (fl2) { rate *= 0.62; vol *= 0.85; const tt = performance.now() * 0.001; if (Math.sin(tt * 43) > 0.78) rate *= 0.6; if (Math.sin(tt * 29) > 0.9) rate *= 0.75; }\n"
    "  try { a.playbackRate = rate; } catch (e) {}\n"
    "  a.volume = Math.max(0, Math.min(1, vol));\n"
    "}\n"
    "function spawnTransmetro(slot) {\n"
    "  if (!S.scene.textures.exists('busTransmetro')) return false;\n"
    "  const horiz = Math.random() < 0.5;\n"
    "  let x, y, dir;\n"
    "  if (horiz) {\n"
    "    dir = Math.random() < 0.5 ? 0 : 2;\n"
    "    y = MUR;\n"
    "    x = Phaser.Math.Clamp(S.car.x + (Math.random() < 0.5 ? -1 : 1) * Phaser.Math.Between(500, 950), ST_X0[MUR] + 90, ST_X1[MUR] - 90);\n"
    "    if (Math.abs(x - S.car.x) < 430) return false;\n"
    "  } else {\n"
    "    dir = Math.random() < 0.5 ? 1 : 3;\n"
    "    x = OLA;\n"
    "    y = Phaser.Math.Clamp(S.car.y + (Math.random() < 0.5 ? -1 : 1) * Phaser.Math.Between(500, 950), AV_TOP[OLA] + 90, AV_BOT[OLA] - 90);\n"
    "    if (Math.abs(y - S.car.y) < 430) return false;\n"
    "  }\n"
    "  if (S.phase > 0 && floodKeyAt(x, y, S.phase)) return false;\n"
    "  for (const t of S.trafficPool) if (t.active && Phaser.Math.Distance.Between(x, y, t.im.x, t.im.y) < 120) return false;\n"
    "  slot.kind = 'tm';\n"
    "  slot.tex = 'busTransmetro';\n"
    "  slot.active = true;\n"
    "  slot.dir = dir;\n"
    "  slot.cur = 0;\n"
    "  slot.cool = 0;\n"
    "  slot.lastCross = '';\n"
    "  slot.cruise = Phaser.Math.Between(125, 160);\n"
    "  const im = slot.im;\n"
    "  im.setPosition(x, y);\n"
    "  setTrafficPose(slot);\n"
    "  im.body.enable = true;\n"
    "  im.setActive(true); im.setVisible(true);\n"
    "  im.setDepth(100 + y + 13);\n"
    "  return true;\n"
    "}\n"
    "// ===== GRÚA ANIMADA =====\n"
    "function gruaAnim(done) {\n"
    "  S.gruaBusy = true;\n"
    "  const sc = S.scene, car = S.car;\n"
    "  showAlert('🚨 ¡La grúa viene en camino!', 2600);\n"
    "  try { const ni = radioIdx < 0 ? Math.floor(Math.random() * RADIOS.length) : (radioIdx + 1) % RADIOS.length; playRadio(ni); } catch (e) {}\n"
    "  try { if (car.body) { car.body.setVelocity(0, 0); car.body.enable = false; } } catch (e) {}\n"
    "  const dxT = TALLER.x - car.x, dyT = TALLER.y - car.y, dT = Math.hypot(dxT, dyT) || 1;\n"
    "  let gx = car.x + dxT / dT * 640, gy = car.y + dyT / dT * 640;\n"
    "  const g = sc.add.image(gx, gy, 'grua').setDepth(6.5);\n"
    "  const cable = sc.add.graphics().setDepth(6.4);\n"
    "  let fase = 'ir', tF = 0;\n"
    "  const ev = sc.time.addEvent({ delay: 30, loop: true, callback: () => {\n"
    "    tF += 30;\n"
    "    if (fase === 'ir') {\n"
    "      const dx = car.x - gx, dy = car.y - gy, d = Math.hypot(dx, dy), paso = 310 * 0.03;\n"
    "      if (d < 60) { fase = 'enganche'; tF = 0; }\n"
    "      else { gx += dx / d * paso; gy += dy / d * paso; }\n"
    "      g.setPosition(gx, gy); g.setAngle(Math.atan2(car.y - gy, car.x - gx) * 180 / Math.PI);\n"
    "    } else if (fase === 'enganche') {\n"
    "      cable.clear(); cable.lineStyle(2, 0x222222, 0.9); cable.lineBetween(gx, gy, car.x, car.y);\n"
    "      if (tF > 650) { fase = 'llevar'; tF = 0; }\n"
    "    } else if (fase === 'llevar') {\n"
    "      const ux = dxT / dT, uy = dyT / dT, paso = 250 * 0.03;\n"
    "      gx += ux * paso; gy += uy * paso;\n"
    "      car.setPosition(gx - ux * 54, gy - uy * 54);\n"
    "      car.setAngle(Math.atan2(uy, ux) * 180 / Math.PI);\n"
    "      g.setPosition(gx, gy); g.setAngle(Math.atan2(uy, ux) * 180 / Math.PI);\n"
    "      cable.clear(); cable.lineStyle(2, 0x222222, 0.9); cable.lineBetween(gx, gy, car.x, car.y);\n"
    "      if (tF > 1300) {\n"
    "        fase = 'fin';\n"
    "        sc.tweens.add({ targets: [g, car], alpha: 0, duration: 380, onComplete: () => {\n"
    "          ev.remove(); cable.destroy(); g.destroy(); car.setAlpha(1);\n"
    "          try { if (car.body) car.body.enable = true; } catch (e) {}\n"
    "          S.gruaBusy = false; done();\n"
    "        } });\n"
    "      }\n"
    "    }\n"
    "  } });\n"
    "}\n"
    "function tow(reason) { if (S.gruaBusy || S.sweptBusy) return; gruaAnim(function () { towReal(reason); if (S.misionActiva && typeof fallarMisionArroyo === 'function') fallarMisionArroyo(); }); }\n"
    "function riverLoss() { if (S.gruaBusy || S.sweptBusy) return; gruaAnim(function () { riverLossReal(); }); }\n"
    "// ===== DESTINOS FUERA DEL ARROYO =====\n"
    "function enArroyo(p) { for (const k of Object.keys(FLOODS)) { if (ELIM.has(k)) continue; const r = floodRect(k, 3); if (r && p.x > r.x0 && p.x < r.x1 && p.y > r.y0 && p.y < r.y1) return true; } return false; }\n"
    "function led() { if (!S.ledger) S.ledger = { servicios: 0, gruas: 0, danos: 0, multas: 0, impuestos: 0, saltos: 0 }; return S.ledger; }\n"
    "function contribGoal() { return CANAL_COSTS[Math.min(ELIM.size, CANAL_COSTS.length - 1)]; }\n"
    "function riverLoss() {\n"
    "  if (S.sweptBusy) return;\n"
    "  S.sweptBusy = true;\n"
    "  S.money -= 270;\n"
    "  led().gruas += 120; led().danos += 90; led().impuestos += 60;\n"
    "  S.contrib = (S.contrib || 0) + 60;\n"
    "  if (S.mission) { S.mission = null; S.person.setVisible(false); S.ring.setVisible(false); el('timerWrap').style.display = 'none'; el('missionText').textContent = '🚖 Busca un pasajero'; }\n"
    "  showAlert('🌊 ¡EL ARROYO TE LLEVÓ AL RÍO! Grúa $120 + daños $90 + impuesto $60', 4500);\n"
    "  sfxPlay('ahogado', 0.9);\n"
    "  if (S.car.body.reset) S.car.body.reset(TALLER.x, TALLER.y); else S.car.setPosition(TALLER.x, TALLER.y);\n"
    "  S.integrity = 60; S.fSpeed = 0; S.stalled = false; S.stallMeter = 0;\n"
    "  updateHUD(); actuBarra(true);\n"
    "  setTimeout(() => { S.sweptBusy = false; if (S.misionActiva && typeof fallarMisionArroyo === 'function') fallarMisionArroyo(); else spawnPickup(900); }, 700);\n"
    "}\n"
    "function creaBarraContrib() {}\n"
    "function actuBarra(force) {}\n"
    "function openTaller() { /* Taller eliminado 2026-10-28: sin panel; cae al menú lateral. */\n"
    "  try { if (S && S.started) openPausa(); } catch (e) {}\n"
    "  return;\n"
    "}\n"
    "function openTallerEliminado() {\n"
    "  if (!S || !S.started) return;\n"
    "  let p = document.getElementById('tallerPanel');\n"
    "  if (!p) {\n"
    "    const st = document.createElement('style');\n"
    "    st.textContent = '#tallerPanel{position:fixed;inset:0;z-index:200;display:flex;align-items:center;justify-content:center;background:rgba(5,8,10,.72);font-family:Nunito,Arial,sans-serif}#tallerCard{background:#14201a;color:#e8f5e9;border:2px solid #2e7d32;border-radius:16px;max-width:92vw;width:430px;max-height:92vh;overflow:auto;padding:18px 20px;box-shadow:0 12px 40px rgba(0,0,0,.5)}#tallerCard h2{margin:0 0 4px;font-size:21px}#tallerCard table{width:100%;border-collapse:collapse;font-size:14px;margin:8px 0}#tallerCard td{padding:3px 2px;border-bottom:1px solid #24402c}#tallerCard td.n{text-align:right;font-weight:800}#tallerCard .canal{width:100%;margin:4px 0;background:#2e7d32;color:#fff;border:0;border-radius:8px;padding:8px;font-weight:800;cursor:pointer;font-family:inherit}#tallerCard .canal:disabled{background:#37474f;cursor:default;opacity:.75}#tallerCard .cerrar{width:100%;margin-top:8px;background:#ffb300;color:#212121;border:0;border-radius:8px;padding:10px;font-weight:900;cursor:pointer;font-size:15px;font-family:inherit}';\n"
    "    document.head.appendChild(st);\n"
    "    p = document.createElement('div'); p.id = 'tallerPanel'; p.innerHTML = '<div id=tallerCard></div>'; document.body.appendChild(p);\n"
    "  }\n"
    "  const L = led(), g = contribGoal(), c = Math.round(S.contrib || 0);\n"
    "  let rows = '<tr><td>🚖 Servicios</td><td class=n>+$' + L.servicios + '</td></tr>'\n"
    "    + '<tr><td>🪂 Bonos por saltos</td><td class=n>+$' + L.saltos + '</td></tr>'\n"
    "    + '<tr><td>🚨 Grúas</td><td class=n>−$' + L.gruas + '</td></tr>'\n"
    "    + '<tr><td>🔩 Daños</td><td class=n>−$' + L.danos + '</td></tr>'\n"
    "    + '<tr><td>🚧 Multas (postes y botes)</td><td class=n>−$' + L.multas + '</td></tr>'\n"
    "    + '<tr><td>🏗️ Impuestos a canalización</td><td class=n>−$' + L.impuestos + '</td></tr>';\n"
    "  let list = '';\n"
    "  for (const k of Object.keys(FLOODS)) {\n"
    "    if (ELIM.has(k)) list += '<button class=canal disabled>✅ Arroyo de ' + FLOOD_NAMES[k] + ' — CANALIZADO</button>';\n"
    "    else list += '<button class=canal data-k=' + k + (c >= g ? '' : ' disabled') + '>🏗️ Canalizar el arroyo de ' + FLOOD_NAMES[k] + ' ($' + g + ')</button>';\n"
    "  }\n"
    "  if (ELIM.size >= Object.keys(FLOODS).length) list = '<p style=text-align:center;font-weight:900>🎉 ¡BARRANQUILLA LIBRE DE ARROYOS! 🎉</p>' + list;\n"
    "  document.getElementById('tallerCard').innerHTML = '<h2>Taller</h2>' + misionStatsTallerHTML() + '<button class=canal id=btnTallerMision>▶ Comenzar misión</button><button class=canal id=btnTallerVer>📋 Ver misiones</button>' + '<div style=font-size:14px;margin-top:12px><b>Balance: $' + Math.round(S.money) + '</b> · Fondo: <b>$' + c + ' / $' + g + '</b></div>' + '<div style=font-size:13px;opacity:.85;margin-bottom:6px>Los impuestos de cada servicio financian la canalización de los arroyos.</div>' + list;\n"
    "  p.style.display = 'flex';\n"
    "  p.querySelectorAll('.canal[data-k]').forEach(b => b.addEventListener('click', () => canalizar(b.getAttribute('data-k'))));\n"
    "  document.getElementById('btnTallerMision').addEventListener('click', () => { closeTaller(); startMision(misionParaEmpezar()); });\n"
    "  document.getElementById('btnTallerVer').addEventListener('click', () => { closeTaller(); openPausa(); });\n"
    "  S.scene.scene.pause();\n"
    "  engineMute();\n"
    "}\n"
    "function closeTaller() { const p = document.getElementById('tallerPanel'); if (p) p.style.display = 'none'; if (S && S.scene) S.scene.scene.resume(); }\n"
    "function canalizar(k, desdeLateral) {\n"
    "  const g = contribGoal();\n"
    "  if (!S || (S.contrib || 0) < g || ELIM.has(k)) return;\n"
    "  S.contrib -= g; ELIM.add(k);\n"
    "  const w = { la21: S.water, donjuan: S.waterDJ, leon: S.waterLN, c84: S.water84, c72: S.water72, c38: S.water38 }[k];\n"
    "  if (w) { try { w.setAlpha(0); w.setDisplaySize(1, 1); const f = () => w; w.setAlpha = f; w.setDisplaySize = f; } catch (e) {} }\n"
    "  const fy = FLOODS[k].kind === 'h' ? FLOODS[k].y : null;\n"
    "  if (S.scene) for (const o of [...S.scene.children.list]) { if (o.type !== 'Text' || !o.text) continue; if (fy !== null && o.text.indexOf('ARROYO') >= 0 && Math.abs(o.y - fy) < 6) o.destroy(); if (k === 'la21' && o.text.indexOf('SALAO') >= 0) o.destroy(); }\n"
    "  if (ELIM.size >= Object.keys(FLOODS).length) showAlert('🎉🏗️ ¡BARRANQUILLA LIBRE DE ARROYOS! ¡Lo lograste!', 5000);\n"
    "  else showAlert('🏗️✅ ¡Arroyo de ' + FLOOD_NAMES[k] + ' CANALIZADO! Quedan ' + (Object.keys(FLOODS).length - ELIM.size), 3400);\n"
    "  actuBarra(true); try { openPausa(); } catch (e) {}\n"
    "}\n"
    "function mecanicaObjetivo(time, dt) {\n"
    "  if (!S || !S.started || S.sweptBusy) return;\n"
    "  const car = S.car;\n"
    "  actuBarra(false);\n"
    "  S.playTime = (S.playTime || 0) + dt;\n"
    "  if ((S.contrib || 0) >= contribGoal() && ELIM.size < Object.keys(FLOODS).length && !S.fundReady) { S.fundReady = true; showAlert('🏗️ ¡Fondo completo! Abre el menú de misiones para canalizar un arroyo', 4200); }\n"
    "  if ((S.contrib || 0) < contribGoal()) S.fundReady = false;\n"
    
    "  for (const r of RAMPS) { const want = S.phase === 3 && !ELIM.has(r.key); if (r.g && r.g.visible !== want) r.g.setVisible(want); }\n"
    "  if (!S.rushNext) S.rushNext = time + 80000;\n"
    "  if (time >= S.rushNext) { S.rushUntil = time + 22000; S.rushNext = time + Phaser.Math.Between(110000, 170000); showAlert('🚗 ¡Hora pico! Tráfico pesado', 2400); }\n"
    "  if (S.mission && S.mission.stage === 'pickup' && S.phase === 3 && !S.mission.swept) {\n"
    "    const fk = floodKeyAt(S.mission.spot.x, S.mission.spot.y, 3);\n"
    "    if (fk) {\n"
    "      S.mission.swept = true;\n"
    "      const fc = floodCurrent(fk, 3);\n"
    "      S.scene.tweens.add({ targets: S.person, x: S.person.x + fc.x * 0.9, y: S.person.y + fc.y * 0.9, alpha: 0, duration: 900, onComplete: () => { S.person.setVisible(false); S.person.setAlpha(1); } });\n"
    "      showAlert('🌊 ¡El arroyo se llevó al pasajero!', 2600);\n"
    "      S.mission = null; S.ring.setVisible(false);\n"
    "      el('missionText').textContent = '🚖 Busca otro pasajero';\n"
    "      S.scene.time.delayedCall(1600, () => spawnPickup(500));\n"
    "    }\n"
    "  }\n"
    "  if (S.mission && S.mission.stage === 'pickup' && !(S.airT > 0)) {\n"
    "    const d = Phaser.Math.Distance.Between(car.x, car.y, S.mission.spot.x, S.mission.spot.y);\n"
    "    if (d < 300 && !S.spotNear) { S.spotNear = true; S.taxiAlt = !S.taxiAlt; if (S.taxiAlt) sfxPlay('taxi', 0.9); else sfxPlay('silbido', 0.75); }\n"
    "    else if (d > 380) S.spotNear = false;\n"
    "  } else S.spotNear = false;\n"
    "  if (S.airT > 0) {\n"
    "    S.airT -= dt;\n"
    "    const prog = 1 - Math.max(0, S.airT) / 0.62;\n"
    "    const sc = 1 + 0.38 * Math.sin(Math.PI * Math.min(1, prog));\n"
    "    car.setDisplaySize(54 * sc, 28 * sc);\n"
    "    const fk = S.phase > 0 ? floodKeyAt(car.x, car.y, S.phase) : null;\n"
    "    if (fk && fk === S.airKey) S.airCrossed = true;\n"
    "    if (S.airT <= 0) {\n"
    "      car.setDisplaySize(54, 28);\n"
    "      if (S.airCrossed) {\n"
    "        S.money += 40; led().saltos += 40; updateHUD();\n"
    "        if (S.mission && S.mission.stage === 'dropoff') S.mission.rampBonus = true;\n"
    "        showAlert('🪂 ¡Saltaste el arroyo! +$40', 2200);\n"
    "      }\n"
    "      S.airCrossed = false;\n"
    "    }\n"
    "  } else {\n"
    "    for (const r of RAMPS) {\n"
    "      if (ELIM.has(r.key) || S.phase !== 3 || !floodRect(r.key, 3)) continue;\n"
    "      if (Math.abs(car.x - r.x) < 30 && Math.abs(car.y - r.y) < 30) {\n"
    "        const vx = car.body.velocity.x, vy = car.body.velocity.y;\n"
    "        const ok = (r.dir === 'S' && vy > 120) || (r.dir === 'N' && vy < -120) || (r.dir === 'E' && vx > 120) || (r.dir === 'W' && vx < -120);\n"
    "        if (ok) { S.airT = 0.62; S.airKey = r.key; S.airCrossed = false; sfxPlay('salto', 0.85); if (S.misionActiva && S.misionActiva.tipo === 'saltos' && S.mission && S.mission.stage === 'dropoff') { S.misionSaltos = (S.misionSaltos || 0) + 1; if (S.misionSaltos >= S.misionActiva.objetivo) misionCompletada(S.misionActiva); } break; }\n"
    "      }\n"
    "    }\n"
    "  }\n"
    "}\n")

# minimap
a = s.index(" c.fillStyle = '#22391f';")
b = s.index("c.fillRect(4300, 1410, 1600, 120);") + len("c.fillRect(4300, 1410, 1600, 120);")
mini = """ c.fillStyle = '#22391f';
 c.fillRect(0, 0, WORLD_W, WORLD_H);
 c.fillStyle = '#2f6d9e';
 c.fillRect(0, 0, WORLD_W, SEA_H);
 c.fillRect(RIVER_X0, SEA_H, RIVER_X1 - RIVER_X0, WORLD_H - SEA_H);
 c.fillStyle = '#d9c07a';
 c.fillRect(0, SEA_H, RIVER_X0, 70);
 c.fillStyle = '#2e6b8a';
 c.beginPath(); c.ellipse(1480, 292, 430, 46, 0, 0, Math.PI * 2); c.fill();
 c.fillStyle = '#3f7a45';
 c.fillRect(3098, 700, RIVER_X0 - 3098, 1412);
 c.fillStyle = '#3d5a36';
 AVENUES.forEach(x => c.fillRect(x - 26, AV_TOP[x], 52, AV_BOT[x] - AV_TOP[x]));
 ALL_STREETS.forEach(y => c.fillRect(ST_X0[y], y - 26, ST_X1[y] - ST_X0[y], 52));
 c.strokeStyle = '#3d5a36';
 c.lineWidth = 100;
 c.beginPath();
 c.moveTo(ARC[0][0], ARC[0][1]);
 for (let k = 1; k < ARC.length; k++) c.lineTo(ARC[k][0], ARC[k][1]);
 c.stroke();
 c.lineWidth = 60;
 c.beginPath();
 c.moveTo(0, 335); c.lineTo(560, 352); c.lineTo(752, 524); c.stroke();
 c.beginPath(); c.moveTo(RIO_X, 2160); c.lineTo(RIO_X, 760); c.lineTo(RIO_X - 45, 608); c.lineTo(3060, 562); c.stroke();
 c.beginPath(); c.moveTo(3050, 560); c.lineTo(3050, 285); c.stroke();
 c.fillStyle = '#8fb8c9';
 c.fillRect(ST_X0[MUR], MUR - 14, ST_X1[MUR] - ST_X0[MUR], 28);
 c.fillRect(OLA - 14, AV_TOP[OLA], 28, SOLEDAD_STREET - AV_TOP[OLA]);
 c.fillStyle = '#3d5a36';
 c.fillRect(RIO_X, 2160 - 50, WORLD_W - RIO_X, 100);"""
s = s[:a] + mini + s[b:]
rep("  if (fSpeed > maxF) fSpeed = Math.max(maxF, fSpeed - 280 * dt);",
    "  if (fSpeed > maxF) fSpeed = Math.max(maxF, fSpeed - ((inWater && S.phase >= 2) ? 950 : 280) * dt);")
rep("  if (fl) { const fc = floodCurrent(fl, S.phase); nvx += fc.x * dt; nvy += fc.y * dt; }",
    "  if (fl) { const fc = floodCurrent(fl, S.phase); const boost = S.phase === 3 ? 3.6 : S.phase === 2 ? 2.2 : 1; nvx += fc.x * boost * dt; nvy += fc.y * boost * dt; if (S.phase === 2) { const wob = Math.sin(time * 0.008) * 0.45 * Math.hypot(fc.x, fc.y); if (fc.x !== 0) nvy += wob * dt; else nvx += wob * dt; } }")
rep("  if (S.phase > 0) S.water.tilePositionY -= (S.phase === 2 ? 340 : 120) * dt;",
    "  if (S.phase > 0) S.water.tilePositionY -= (S.phase === 3 ? 720 : S.phase === 2 ? 600 : 130) * dt;")
rep("  if (S.phase === 2) { S.waterDJ.tilePositionX -= 380 * dt; S.waterLN.tilePositionX -= 300 * dt; }",
    "  if (S.phase === 2) { S.waterDJ.tilePositionX -= 540 * dt; S.waterLN.tilePositionX += 460 * dt; }\n  if (S.phase === 3) { S.waterDJ.tilePositionX -= 660 * dt; S.waterLN.tilePositionX += 540 * dt; }")
rep("<div id=\"btnDrift\">DER</div>", "")
# Sin textos en los pedales (Rafael, 2026-10-29): al sostenerlos el
# sistema creía que se estaba seleccionando texto de la página.
rep('<div class="lbl">FRENO</div>', '<div class="lbl"></div>')
rep('<div class="lbl">ACELERADOR</div>', '<div class="lbl"></div>')
rep("para acelerar y DER para derrapar", "para acelerar y ESPACIO para derrapar")
rep("ESPACIO / botón DER, o freno sostenido yendo rápido (truco móvil tipo CW)", "ESPACIO, o freno sostenido yendo rápido (truco móvil tipo CW)")
rep("<h2>Prototipo · Conduce en Barranquilla… hasta que llueve</h2>", "")
# Portada sin flash de la version vieja (2026-10-24, reporte de Rafael): el
# <style> que oculta estos parrafos vive al FINAL del archivo (3 MB), asi
# que en conexiones lentas la portada vieja se veia segundos antes de que
# llegara el estilo. Con display:none INLINE quedan ocultos desde el primer
# pintado; la regla de hudfix queda como respaldo.
rep("<p>🚖 Recoge pasajeros", "<p style=\"display:none\">🚖 Recoge pasajeros")
rep("<p class=\"carHint\">", "<p class=\"carHint\" style=\"display:none\">")
rep("🚖 Recoge pasajeros y llévalos a su destino antes de que se acabe el tiempo.<br>",
    "🚖 Recoge pasajeros y llévalos a su destino antes de que se acabe el tiempo: el 30% de cada tarifa alimenta el <b>fondo de canalización</b>.<br>")
rep("🌧️ Cuando llueva, <b>la Cra 21, el Don Juan, el León y el Rebolo se vuelven arroyos</b>: la corriente te arrastra. ¡Busca vías alternas o cruza con impulso!<br>",
    "🏗️ <b>Objetivo:</b> con ese fondo, canaliza desde el menú de misiones los 3 arroyos de la ciudad — <b>León</b> al norte, <b>Don Juan</b> y <b>El Salao</b> al sur — y libérala de las inundaciones.<br>")
rep("🚗 Hay tráfico en la ciudad: no te estrelles… y ojo con los trancones junto a los arroyos. Por Murillo y la Cra 46 va el carril del <b>Transmetro</b> 🚏<br>",
    "")
rep("🕳️ Si el arroyo te lleva al desagüe del sur, pagas grúa.<br><br>",
    "🕳️ Si la corriente te lleva al río o al desagüe, pagas grúa y daños.<br><br>")
rep("🕳️ Si la corriente te lleva al río o al desagüe, pagas grúa y daños.<br><br>",
    "🕳️ Si la corriente te lleva al río o al desagüe, pagas grúa y daños.<br>\n  🎯 Ahora se juega por <b>MISIONES</b>: abre el menú ☰ para elegir Taxi, Particular o Bus.<br><br>")
rep("⌨️ <b>Flechas o WASD</b> para conducir · <b>ESPACIO</b> = freno de mano para derrapar<br>",
    "⌨️ <b>Flechas o WASD</b> para conducir · <b>ESPACIO</b> = freno de mano · <b>Esc/P</b> = menú<br>")
rep("📱 En el celular: <b>joystick</b> para girar (bájalo para frenar), <b>pedal</b> para acelerar y ESPACIO para derrapar</p>",
    "📱 En el celular: <b>joystick</b> para girar (bájalo para frenar) y <b>pedales</b> de acelerador y freno. El menú ☰ está arriba a la izquierda</p>")
rep("const SFX_EL = {};", "const BUS_SPRITES = { busCoochofal: '" + _img64('/home/hatch/workspace/goals/killa-drivers/files/buses/sprites/busCoochofal.png') + "', busSobusa: '" + _img64('/home/hatch/workspace/goals/killa-drivers/files/buses/sprites/busSobusa.png') + "', busTransmetro: '" + _img64('/home/hatch/workspace/goals/killa-drivers/files/buses/sprites/busTransmetro.png') + "' };\nconst SFX_EL = {};")
rep("  scene.textures.addBase64('carAzul', CAR_SPRITES.azul);",
    "  scene.textures.addBase64('carAzul', CAR_SPRITES.azul);\n  scene.textures.addBase64('busCoochofal', BUS_SPRITES.busCoochofal);\n  scene.textures.addBase64('busSobusa', BUS_SPRITES.busSobusa);\n  scene.textures.addBase64('busTransmetro', BUS_SPRITES.busTransmetro);\n  { const gg = scene.add.graphics(); gg.fillStyle(0xf5f5f5, 1); gg.fillRect(2, 10, 30, 16); gg.fillStyle(0xef6c00, 1); gg.fillRect(46, 7, 22, 22); gg.fillStyle(0x90caf9, 1); gg.fillRect(58, 10, 8, 16); gg.fillStyle(0xef6c00, 1); gg.fillRect(30, 4, 8, 28); gg.lineStyle(4, 0x37474f, 1); gg.lineBetween(34, 6, 8, 16); gg.fillStyle(0x212121, 1); gg.fillCircle(16, 3, 5); gg.fillCircle(16, 33, 5); gg.fillCircle(56, 3, 5); gg.fillCircle(56, 33, 5); gg.generateTexture('grua', 72, 36); gg.destroy(); }")
rep("  const key = t.tex || (t.tex = pickTrafficTex());\n  im.setScale(1); im.clearTint();\n",
    "  const key = t.tex || (t.tex = pickTrafficTex());\n  im.setScale(1); im.clearTint();\n  if ((t.kind === 'bus' || t.kind === 'tm') && key && S.scene.textures.exists(key)) {\n    im.setTexture(key);\n    im.setDisplaySize(t.kind === 'tm' ? 150 : 102, 30);\n    const fw = im.width, fh = im.height;\n    if (t.dir === 0) { im.setAngle(0); im.body.setSize(fw, fh); }\n    if (t.dir === 2) { im.setAngle(180); im.body.setSize(fw, fh); }\n    if (t.dir === 1) { im.setAngle(90); im.body.setSize(fh, fw); }\n    if (t.dir === 3) { im.setAngle(-90); im.body.setSize(fh, fw); }\n    return;\n  }\n")
rep("function spawnTraffic() {\n  const slot = S.trafficPool.find(t => !t.active);\n  if (!slot) return;\n",
    "function spawnTraffic() {\n  const slot = S.trafficPool.find(t => !t.active);\n  if (!slot) return;\n  if (Math.random() < 0.12 && spawnTransmetro(slot)) return;\n")
rep("  slot.active = true; slot.dir = dir; slot.cur = 0; slot.cool = 0; slot.lastCross = '';",
    "  slot.kind = 'car'; slot.tex = null;\n  if (S.scene.textures.exists('busCoochofal') && Math.random() < 0.26) { slot.kind = 'bus'; slot.tex = Math.random() < 0.5 ? 'busCoochofal' : 'busSobusa'; }\n  slot.active = true; slot.dir = dir; slot.cur = 0; slot.cool = 0; slot.lastCross = '';")
rep("  slot.cruise = Phaser.Math.Between(150, 215);",
    "  slot.cruise = Phaser.Math.Between(150, 215);\n  if (slot.kind === 'bus') slot.cruise = Phaser.Math.Between(105, 145);")
rep("    // ¿Lo agarró un arroyo? La corriente se lo lleva\n    const fl = S.phase > 0 ? floodKeyAt(im.x, im.y, S.phase) : null;",
    "    // TRANSMETRO: nunca entra a un arroyo; espera a que baje el agua\n    if (t.kind === 'tm' && S.phase > 0) {\n      const dd0 = DIRS[t.dir];\n      if (floodKeyAt(im.x, im.y, S.phase) || floodKeyAt(im.x + dd0.x * 108, im.y + dd0.y * 108, S.phase)) { t.cur = 0; im.body.setVelocity(0, 0); continue; }\n    }\n    // ¿Lo agarró un arroyo? La corriente se lo lleva\n    const fl = S.phase > 0 ? floodKeyAt(im.x, im.y, S.phase) : null;")
rep("        if (Math.random() < 0.22) turnTraffic(t, cx, cy);",
    "        if (t.kind !== 'tm' && Math.random() < 0.22) turnTraffic(t, cx, cy);")
rep("function tow(reason) {\n  if (S.sweptBusy) return;", "function towReal(reason) {\n  if (S.sweptBusy) return;")
rep("  if (S.mission && S.mission.stage === 'dropoff') { S.mission = null; spawnPickup(1400); }", "  if (S.mission && S.mission.stage === 'dropoff') { S.mission = null; if (!S.misionActiva) spawnPickup(1400); }")
rep("function riverLoss() {\n  if (S.sweptBusy) return;", "function riverLossReal() {\n  if (S.sweptBusy) return;")
rep("function startDropoff() {\n  const from = S.mission.spot;\n  const dest = randomSpot(from, 750);", "function startDropoff() {\n  const from = S.mission.spot;\n  let dest = randomSpot(from, 750);\n  for (let i = 0; i < 24 && enArroyo(dest); i++) dest = randomSpot(from, 750);")
rep("<h1>🌧️ ¡CUIDADO CON EL ARROYO!</h1>", "<h1>🌧️ ¡CUIDADO CON LOS ARROYOS!</h1>")
rep("<title>¡Cuidado con el Arroyo! — Prototipo · Las Vainas del Rafa</title>", "<title>Killa Drivers · Las Vainas del Rafa</title>")
# Miniatura al compartir por WhatsApp (2026-10-24, pedido de Rafael): Open
# Graph con la portada del juego. La imagen se despliega como /portada.jpg
# en el mismo sitio (WhatsApp exige URL absoluta).
rep("<title>Killa Drivers · Las Vainas del Rafa</title>",
    "<title>Killa Drivers · Las Vainas del Rafa</title>\n<meta property='og:type' content='website'>\n<meta property='og:url' content='https://killadrivers.netlify.app/'>\n<meta property='og:title' content='Killa Drivers'>\n<meta property='og:description' content='Conduce en Barranquilla, completa misiones, y ten cuidado con los arroyos!'>\n<meta property='og:image' content='https://killadrivers.netlify.app/portada-og.jpg'>\n<meta property='og:image:width' content='1200'>\n<meta property='og:image:height' content='630'>\n<meta property='og:image:alt' content='Killa Drivers: taxi, bus y particular saltando el arroyo en Barranquilla'>\n<meta name='twitter:card' content='summary_large_image'>")
rep("¡CUIDADO CON EL ARROYO! — v4 mundo abierto", "KILLA DRIVERS — mundo abierto")
rep("const RADIOS = [", "const RADIO_ICONS = { innovacion: '" + _img64('/home/hatch/workspace/goals/killa-drivers/files/radios/innovacion.png') + "', zonasalsa: '" + _img64('/home/hatch/workspace/goals/killa-drivers/files/radios/zonasalsa.png') + "', mix: '" + _img64('/home/hatch/workspace/goals/killa-drivers/files/radios/mix.png') + "', radioacktiva: '" + _img64('/home/hatch/workspace/goals/killa-drivers/files/radios/radioacktiva.png') + "' };\nconst RADIOS = [")
rep("<h1>\U0001F327\uFE0F \u00A1CUIDADO CON LOS ARROYOS!</h1>", "<h1 style='font-size:clamp(32px,8vw,54px);color:#ffd83d;margin-bottom:12px;font-weight:900;letter-spacing:.5px;text-shadow:0 1px 0 #c49002,0 2px 0 #a87c02,0 3px 0 #8a6502,0 4px 0 #6d5102,0 5px 0 #503c01,0 6px 3px rgba(0,0,0,.55),0 12px 22px rgba(0,0,0,.5)'>KILLA DRIVERS</h1><img id=coverImg alt='Killa Drivers' src='" + _webp64('/home/hatch/workspace/goals/killa-drivers/files/titulo-killa-spark-ethnocentric-transparente.webp') + "' style='display:block;width:min(98vw,960px);height:auto;margin:0 auto 10px;border:0;box-shadow:none'>")
# ===== KILLA DRIVERS: bus jugable + gancho de misiones (Rafael, 2026-10-24) =====
rep("const CAR_KEYS = { taxi: 'carTaxi', rojo: 'carRojo', azul: 'carAzul' };",
    "const CAR_KEYS = { taxi: 'carTaxi', rojo: 'carRojo', azul: 'carAzul', bus: 'busSobusa' };")
rep("function applyPlayerCar() {\n  if (!S || !S.car) return;\n  S.car.setTexture(CAR_KEYS[CAR_CHOICE]);\n  S.car.setDisplaySize(54, 28);\n}",
    "function applyPlayerCar() {\n  if (!S || !S.car) return;\n  S.car.setTexture(CAR_KEYS[CAR_CHOICE]);\n  if (CAR_CHOICE === 'bus') S.car.setDisplaySize(102, 30); else S.car.setDisplaySize(54, 28);\n  const h = document.getElementById('hudHealth');\n  if (h && h.firstChild && h.firstChild.nodeType === 3) h.firstChild.textContent = CAR_CHOICE === 'bus' ? '🚌 Bus ' : (CAR_CHOICE === 'taxi' ? '🚕 Taxi ' : '🚗 Carro ');\n}")
rep("  // El hitbox de Arcade no rota: se intercambia según la orientación del carro\n  const isVertical = Math.abs(f2y) > 0.707;\n  if (isVertical !== S.bodyVertical) {\n    S.bodyVertical = isVertical;\n    if (isVertical) car.body.setSize(80, 168); else car.body.setSize(168, 80);\n  }",
    "  // Hitbox cuadrado (Rafael, 2026-10-27): Arcade no rota el rectángulo y el intercambio 20x42 <-> 42x20 al pasar los 45 grados enganchaba el carro en las esquinas de los bordillos. Un cuadrado no cambia al girar: 28 en taxi/part, 34 en bus.\n  { const sq = CAR_CHOICE === 'bus' ? 34 : 28; car.body.setSize(sq / car.scaleX, sq / car.scaleY); }")
rep("  S.mission = null;\n  S.ring.setVisible(false);\n  el('timerWrap').style.display = 'none';\n  showAlert('✅ ¡Servicio completado! +$' + fare + note, 2600);",
    "  servicioCompletado();\n  S.mission = null;\n  S.ring.setVisible(false);\n  el('timerWrap').style.display = 'none';\n  showAlert('✅ ¡Servicio completado! +$' + fare + note, 2600);")
# ===== MISIONES Y POLICIA (Rafael, 2026-10-24; reemplaza las jornadas) =====
_pol = open('police_b64.txt').read().strip()
rep("const CAR_SPRITES = {", "const POLICE_SPRITE = '" + _pol + "';\nconst CAR_SPRITES = {")
rep("  scene.textures.addBase64('carAzul', CAR_SPRITES.azul);",
    "  scene.textures.addBase64('carAzul', CAR_SPRITES.azul);\n  scene.textures.addBase64('carPolicia', POLICE_SPRITE);")
_mis = open('misiones.js').read().rstrip('\n')
rep("function startGame() {", _mis + "\nfunction startGame() {")
# Modo carrera (Rafael, 2026-10-27): se inyecta tras las misiones y antes
# de startGame, en el mismo script, para compartir S y las funciones.
_car = open('carrera.js').read().rstrip('\n')
rep("function startGame() {", _car + "\nfunction startGame() {")
# Carrera con arroyos (Rafael, 2026-10-30): en carrera NO hay ahogamiento
# del motor ni grúa al taller; el arrastre se resuelve con reaparición
# en la orilla (carrera.js). Se conserva el aviso de arrastre.
rep("    if (along > 110) S.stallMeter = Math.min(1, S.stallMeter + dt / (S.phase === 3 ? 2.6 : 5.5));",
    "    if (along > 110 && !S.carreraActiva) S.stallMeter = Math.min(1, S.stallMeter + dt / (S.phase === 3 ? 2.6 : 5.5));")
rep("  if (S.phase >= 2 && !S.sweptBusy && fl === 'la21' && car.y > WORLD_H - 130) {",
    "  if (S.phase >= 2 && !S.sweptBusy && !S.carreraActiva && fl === 'la21' && car.y > WORLD_H - 130) {")
_mul = open('multi.js').read().rstrip('\n')
rep("function startGame() ", _mul + "\nfunction startGame() ")
rep("  S.startTime = S.scene.time.now;\n  S.rainAt = S.startTime + 28000;",
    "  S.startTime = S.scene.time.now;\n  misionInit();\n  S.rainAt = S.startTime + 28000;")
rep("  if (time - S.minimapAt > 130) { S.minimapAt = time; drawMinimap(); }",
    "  if (time - S.minimapAt > 130) { S.minimapAt = time; drawMinimap(); policeBlips(); busBlips(); }\n  misionTick(time); policeTick(time, delta);")
# Contador de choques de la misión (v2, Rafael 2026-10-27): un impacto con
# chispas cuenta como choque del intento (máx. 1 cada 600 ms).
rep("function spawnPickup(delay) {",
    "function spawnPickup(delay) {\n  if (S.carreraActiva || S.multiActiva) return;")
# El delayedCall interno también debe respetar el modo (si se pidió el
# pasajero justo antes de empezar la partida, el callback llegaría en
# plena carrera/partida). (Rafael, 2026-10-29)
rep("S.scene.time.delayedCall(delay || 0, () => {\n    const spot = randomSpot(null, 0);",
    "S.scene.time.delayedCall(delay || 0, () => {\n  if (S.carreraActiva || S.multiActiva) return;\n    const spot = randomSpot(null, 0);")
# Contador de choques de la misión (v2, Rafael 2026-10-27): un impacto con
# chispas cuenta como choque del intento (máx. 1 cada 600 ms).
rep("  if (speed > 200) emitSparks(car.x, car.y, 6);",
    "  if (speed > 200) emitSparks(car.x, car.y, 6);\n  if (speed > 200 && S.misionActiva && now - (S.misionUltChoque || 0) > 600) { S.misionUltChoque = now; S.misionChoques = (S.misionChoques || 0) + 1; }")

# ===== PORTADA PLANA + GLORIETA LIBRE (Rafael, 2026-10-24) =====
# Título plano y sólido con tipografía llamativa (fuera el efecto 3D).
rep("<h1 style='font-size:clamp(32px,8vw,54px);color:#ffd83d;margin-bottom:12px;font-weight:900;letter-spacing:.5px;text-shadow:0 1px 0 #c49002,0 2px 0 #a87c02,0 3px 0 #8a6502,0 4px 0 #6d5102,0 5px 0 #503c01,0 6px 3px rgba(0,0,0,.55),0 12px 22px rgba(0,0,0,.5)'>KILLA DRIVERS</h1>",
    "")  # Título integrado en la imagen de portada (Pumarejo, 2026-10-28): sin h1 duplicado
# Tráfico: giro dirigido (para la glorieta) + giros forzados en (Vía 40, Calle 90).
rep("function turnTraffic(t, cx, cy) {\n  const left = Math.random() < 0.5;\n  t.dir = left ? (t.dir + 3) % 4 : (t.dir + 1) % 4;",
    "function turnTraffic(t, cx, cy, forceDir) {\n  const left = Math.random() < 0.5;\n  t.dir = forceDir !== undefined ? forceDir : (left ? (t.dir + 3) % 4 : (t.dir + 1) % 4);")
rep("      if (crossId && crossId !== t.lastCross) {\n        t.lastCross = crossId;\n        if (t.kind !== 'tm' && Math.random() < 0.22) turnTraffic(t, cx, cy);\n      }",
    "      if (crossId && crossId !== t.lastCross) {\n        t.lastCross = crossId;\n        // Glorieta de la Vía 40 (Rafael, 2026-10-24): ningún vehículo entra al anillo - antes seguían derecho y desaparecían dentro de la isla. Al norte por la Vía 40 se gira en la Calle 90; al oriente por la Calle 90 se gira al sur por la Vía 40.\n        if (t.kind !== 'tm' && crossId === 'h640' && Math.abs(cx - VIA40_X) < 8 && t.dir === 3) turnTraffic(t, cx, cy);\n        else if (t.kind !== 'tm' && crossId === 'v3050' && t.dir === 0 && Math.abs(cy - 640) < 8) turnTraffic(t, cx, cy, 1);\n        else if (t.kind !== 'tm' && Math.random() < 0.22) turnTraffic(t, cx, cy);\n      }")
# Tráfico en la Vía 40 nace al sur de la Calle 90, para que el giro forzado lo agarre.
rep("    y = Phaser.Math.Clamp(S.car.y + (Math.random() < 0.5 ? -1 : 1) * Phaser.Math.Between(420, 900), AV_TOP[ax] + 60, AV_BOT[ax] - 60);",
    "    y = Phaser.Math.Clamp(S.car.y + (Math.random() < 0.5 ? -1 : 1) * Phaser.Math.Between(420, 900), ax === VIA40_X ? 700 : AV_TOP[ax] + 60, AV_BOT[ax] - 60);")

# ===== GRÚA ACUÁTICA + PATRULLA (Rafael, 2026-10-24) =====
# Bote remolcador: PNG generado con transparencia, registrado como 'gruaAcuatica'.
_boa = open('grua-acuatica.b64').read().strip()
rep("const CAR_SPRITES = {", "const GRUA_ACUATICA_SPRITE = '" + _boa + "';\nconst CAR_SPRITES = {")
rep("  scene.textures.addBase64('carPolicia', POLICE_SPRITE);",
    "  scene.textures.addBase64('carPolicia', POLICE_SPRITE);\n  scene.textures.addBase64('gruaAcuatica', GRUA_ACUATICA_SPRITE);")
# Caer al río: grúa acuática (no solo el arrastre del arroyo Don Juan).
# Zona = río [RIVER_X0, RIVER_X1] × [SEA_H, WORLD_H], fuera del puente (y 2105–2215).
rep("  if (fl && S.phase === 3 && RIVER_FLOW.includes(fl) && car.x > RIVER_X0 - 60 && !S.sweptBusy) riverLoss();",
    "  if (fl && S.phase === 3 && RIVER_FLOW.includes(fl) && car.x > RIVER_X0 - 60 && !S.sweptBusy) riverLoss();\n  if (S.started && !S.gruaBusy && !S.sweptBusy && car.x >= RIVER_X0 && car.x <= RIVER_X1 && car.y >= SEA_H && !(car.y >= 2105 && car.y <= 2215)) rioTow();")
# riverLossReal acepta mensaje (la grúa acuática usa el suyo; el arroyo mantiene el de siempre).
rep("function riverLossReal() {", "function riverLossReal(msg) {")
rep("  showAlert('🌊 ¡EL ARROYO TE LLEVÓ AL RÍO! Grúa $120 + daños $90 + impuesto $60', 4500);",
    "  showAlert(msg || '🌊 ¡EL ARROYO TE LLEVÓ AL RÍO! Grúa $120 + daños $90 + impuesto $60', 4500);")
# Grúa acuática + su disparador, antes de gruaAnim.
_acu = open('grua-acuatica.js').read().rstrip('\n')
rep("function gruaAnim(done) {", _acu + "\nfunction gruaAnim(done) {")

# ===== GRÚA DE LA CIUDAD EN PNG (Rafael, 2026-10-24) =====
# Camión remolque generado (PNG con transparencia) como 'gruaCiudad'.
# La grúa procedural 'grua' queda como respaldo si el PNG fallara.
_ciu = open('grua-ciudad.b64').read().strip()
rep("const CAR_SPRITES = {", "const GRUA_CIUDAD_SPRITE = '" + _ciu + "';\nconst CAR_SPRITES = {")
rep("  scene.textures.addBase64('gruaAcuatica', GRUA_ACUATICA_SPRITE);",
    "  scene.textures.addBase64('gruaAcuatica', GRUA_ACUATICA_SPRITE);\n  scene.textures.addBase64('gruaCiudad', GRUA_CIUDAD_SPRITE);")
rep("  const g = sc.add.image(gx, gy, 'grua').setDepth(6.5);",
    "  const g = sc.add.image(gx, gy, sc.textures.exists('gruaCiudad') ? 'gruaCiudad' : 'grua').setDepth(6.5);\n  g.setScale(84 / g.width);")

# ===== COLISIONES SUAVES (Rafael, 2026-10-27): barreras invisibles y bordillos =====
# Hitbox inicial cuadrado (el del update ya se pone cuadrado cada cuadro).
rep("  S.car.body.setSize(80, 168);", "  S.car.body.setSize(28 / S.car.scaleX, 28 / S.car.scaleY);")
# Desatasco: con el acelerador pisado se puede girar aunque la velocidad sea
# casi cero; antes, al quedar pegado a una esquina con fSpeed = 0, el giro
# exigía |fSpeed| > 12 y el carro quedaba retenido sin poder apuntar fuera.
rep("  if (steer !== 0 && Math.abs(fSpeed) > 12) {\n    const rate = (handbrake ? 245 : 188) * (fSpeed >= 0 ? 1 : -1) * Math.min(1, Math.abs(fSpeed) / 120);",
    "  if (steer !== 0 && (Math.abs(fSpeed) > 12 || upIn)) {\n    const rate = (handbrake ? 245 : 188) * (fSpeed >= 0 ? 1 : -1) * Math.max(0.35, Math.min(1, Math.abs(fSpeed) / 120));")
# Trancón: mismo margen que los parqueados.
rep("if (key && kind === 'V') c.setBodySize(28, 54); else if (key) c.setBodySize(54, 28);", "if (key && kind === 'V') c.setBodySize(24, 46); else if (key) c.setBodySize(46, 24);")


# ===== MOTOR DEL BUS (Rafael, 2026-10-27): grabacion Alexftw123 / Pixabay =====
# Solo cuando CAR_CHOICE === 'bus'; taxi y particular siguen con el sintetizado WebAudio.
rep("function spawnTransmetro(slot) {",
    "function busEngineInit() {\n"
    "  if (typeof CAR_CHOICE !== 'undefined' && CAR_CHOICE !== 'bus') return;\n"
    "  try { if (S.busEl) { if (S.busEl.paused) { const pr = S.busEl.play(); if (pr) pr.catch(() => {}); } return; } const a = sfxEl('busMotor'); a.loop = true; a.volume = 0; S.busEl = a; const pr = a.play(); if (pr) pr.catch(() => {}); } catch (e) {}\n"
    "}\n"
    "function busEngineAudio() {\n"
    "  if (!S.busEl) busEngineInit();\n"
    "  const a = S.busEl; if (!a || !S || !S.started) return;\n"
    "  if (typeof ENG !== 'undefined' && ENG.gain && ENG.ctx) { try { ENG.gain.gain.setTargetAtTime(0, ENG.ctx.currentTime, 0.05); } catch (e) {} }\n"
    "  if (a.paused && !S.stalled) { const pr = a.play(); if (pr) pr.catch(() => {}); }\n"
    "  if (S.stalled) { a.volume = Math.max(0, a.volume - 0.1); return; }\n"
    "  if (S.busRpm == null) { S.busRpm = 0.14; S.busGasS = 0; }\n"
    "  const gas = (S.cursors && S.cursors.up.isDown) || (S.keys && S.keys.up.isDown) || (S.touch && S.touch.gas) ? 1 : 0;\n"
    "  S.busGasS += (gas - S.busGasS) * 0.10;\n"
    "  const ratio = Math.min(1, (S.car ? S.car.body.speed : 0) / 430);\n"
    "  let rpm = 0.14 + S.busGasS * 0.52 + ratio * 0.34;\n"
    "  if (rpm > 1) rpm = 1;\n"
    "  S.busRpm += (rpm - S.busRpm) * 0.12;\n"
    "  let rate = 0.84 + S.busRpm * 0.76;\n"
    "  let vol = 0.36 + S.busGasS * 0.30 + ratio * 0.20;\n"
    "  const fl2 = (S.car && S.phase >= 2) ? floodKeyAt(S.car.x, S.car.y, S.phase) : null;\n"
    "  if (fl2) { rate *= 0.62; vol *= 0.85; const tt = performance.now() * 0.001; if (Math.sin(tt * 43) > 0.78) rate *= 0.6; if (Math.sin(tt * 29) > 0.9) rate *= 0.75; }\n"
    "  try { a.playbackRate = rate; } catch (e) {}\n"
    "  a.volume = Math.max(0, Math.min(1, vol));\n"
    "}\n"
    "function spawnTransmetro(slot) {")

# ===== NUEVA UI v2 EN EL JUEGO VIVO (Rafael, 2026-10-28) =====
# Portada -> JUGAR -> Seleccionar modo -> Misiones o Multijugador local.
# Cada pantalla con botón ATRÁS. Sin emojis en la UI nueva, sin pestañas.
# Solo cáscara de UI: mapa, manejo, misiones, carrera, sonidos y tráfico NO cambian.
# El clic en la portada ya NO arranca el juego (antes lo hacía cualquier clic);
# solo JUGAR abre el modo, y desde Misiones/Multijugador se arranca el juego real.
rep("el('startOverlay').addEventListener('click', startGame);",
    "/* UI v2: el clic en la portada ya no arranca el juego; lo hace JUGAR / Misiones / Carrera */")
rep("scene.input.keyboard.once('keydown', startGame);",
    "scene.input.keyboard.once('keydown', function(){ if (typeof killaUIShow === 'function') killaUIShow('modo'); });")
# Botón TOCA PARA EMPEZAR -> JUGAR + vistas Modo / Misiones / Multijugador dentro de startOverlay
_UI_VIEWS = """
<div class="go" id="uiBtnJugar" onclick="killaUIShow('modo')">JUGAR</div>
<div id="uiModo" class="killaView" style="display:none;width:100%;max-width:430px;text-align:center">
  <div class="killaHdr" style="font-size:clamp(24px,7vw,32px)">SELECCIONAR MODO</div>
  <button class="killaModoBtn killaModoCy" onclick="killaUIShow('misiones')">Misiones</button>
  <button class="killaModoBtn killaModoYl" onclick="killaUIShow('multi')">Multijugador<br>Local</button>
  <div style="text-align:left;margin-top:28px"><button class="killaBack" onclick="killaUIShow('portada')">← ATRÁS</button></div>
</div>
<div id="uiMisiones" class="killaView" style="display:none;width:min(92vw,430px);text-align:left">
  <button class="killaBack" onclick="killaUIShow('modo')">← ATRÁS</button>
  <div class="killaPanel"><div class="killaHdr"><span style="color:#22d3ee">▸</span> MISIONES</div><div id="uiMisionesList"></div>
  <p class="killaNote">Solo se muestran las misiones pendientes. Las de 3 estrellas ya no se muestran. Repite las de 1-2 estrellas para conseguir las 3.</p></div>
</div>
<div id="uiMulti" class="killaView" style="display:none;width:min(92vw,430px);text-align:left">
  <button class="killaBack" onclick="killaUIShow('modo')">← ATRÁS</button>
  <div class="killaPanel"><div class="killaHdr"><span style="color:#22d3ee">▸</span> COPA ARROYO</div>
    <h3 style="margin:14px 0 2px">ELIGE TU AUTO</h3>
    <div class="killaCarSel">
      <button class="killaArrow" onclick="killaMultiVehCambiar(-1)">←</button>
      <div class="killaCarSelCard"><img id="killaMultiVehImg" src="vehiculos/killa-taxi.png" alt="Auto"><div id="killaMultiVehNom">TAXI</div></div>
      <button class="killaArrow" onclick="killaMultiVehCambiar(1)">→</button>
    </div>
    <div class="killaModoCard">
      <img src="prev/carrera.jpg" alt="Copa Arroyo" loading="lazy">
      <div class="killaModoBody"><h3>COPA ARROYO</h3>
      <p class="killaNote">4 trazados contra 3 rivales. Los dos primeros en seco; el 3.º y el 4.º con lluvia y arroyos.</p></div>
    </div>
    <h3 style="margin:14px 0 2px">ELIGE EL TRAZADO</h3>
    <div id="uiCircuitos"></div>
    <div class="killaRow" style="opacity:.65"><div><h3>2 JUGADORES</h3><p>Dos carros en el mismo dispositivo.</p></div><button class="killaBtnDk" disabled>PRÓXIMAMENTE</button></div>
    <div class="killaRow" style="opacity:.65"><div><h3>TORNEO LOCAL</h3><p>3 carreras seguidas, puntos por posición.</p></div><button class="killaBtnDk" disabled>PRÓXIMAMENTE</button></div>
    <div class="killaRow" style="opacity:.65"><div><h3>CONTRARRELOJ</h3><p>Solo contra el reloj, tu mejor vuelta queda guardada.</p></div><button class="killaBtnDk" disabled>PRÓXIMAMENTE</button></div>
    <p class="killaNote">En carrera, el choque no da grúa (integridad mínima 30).</p>
  </div>
</div>
"""
rep('<div class="go">TOCA PARA EMPEZAR</div>', _UI_VIEWS.strip())
# Script de navegación UI v2, antes del cierre del body (después del script principal)
_UI_JS = """
<script>
/* UI v2: navegación Portada -> Modo -> Misiones / Multijugador, con ATRÁS. */
(function(){
  /* Música de menús (Rafael, 2026-10-28): pista 1, Afrobeat Instrumental de Sub_Clair, en bucle, volumen moderado. Suena en portada/menús y se detiene al empezar misión/carrera, donde arranca la emisora. */
  var menuAudio = null;
  window.menuMusicStart = function() { try { if (!menuAudio) { menuAudio = new Audio('menu-musica.mp3'); menuAudio.loop = true; menuAudio.volume = 0.5; } if (menuAudio.paused) { var pr = menuAudio.play(); if (pr && pr.catch) pr.catch(function(){}); } } catch(e){} };
  window.menuMusicStop = function() { try { if (menuAudio) { menuAudio.pause(); menuAudio.currentTime = 0; } } catch(e){} };
  /* Sonido de toque de botones (Rafael, 2026-10-28): blip corto sintetizado con WebAudio, sin archivo. */
  var clickCtx = null;
  window.killaClick = function() { try { var AC = window.AudioContext || window.webkitAudioContext; if (!AC) return; if (!clickCtx) clickCtx = new AC(); var ctx = clickCtx; if (ctx.state === 'suspended') ctx.resume(); var t = ctx.currentTime; var o = ctx.createOscillator(), g = ctx.createGain(); o.type = 'sine'; o.frequency.setValueAtTime(1150, t); o.frequency.exponentialRampToValueAtTime(700, t + 0.08); g.gain.setValueAtTime(0.0001, t); g.gain.exponentialRampToValueAtTime(0.18, t + 0.012); g.gain.exponentialRampToValueAtTime(0.0001, t + 0.12); o.connect(g); g.connect(ctx.destination); o.start(t); o.stop(t + 0.13); } catch(e){} };
  /* Sonido de punto obtenido en multijugador (Rafael, 2026-10-29): dos notas ascendentes (A5->E6), distinto al blip de botones. */
  window.killaPoint = function() { try { var AC = window.AudioContext || window.webkitAudioContext; if (!AC) return; if (!clickCtx) clickCtx = new AC(); var ctx = clickCtx; if (ctx.state === 'suspended') ctx.resume(); var t = ctx.currentTime; var notas = [[880, 0, 0.10], [1318.5, 0.09, 0.16]]; for (var i = 0; i < notas.length; i++) { (function(fr, dl, du){ var o = ctx.createOscillator(), g = ctx.createGain(); o.type = 'sine'; o.frequency.setValueAtTime(fr, t + dl); g.gain.setValueAtTime(0.0001, t + dl); g.gain.exponentialRampToValueAtTime(0.22, t + dl + 0.015); g.gain.exponentialRampToValueAtTime(0.0001, t + dl + du); o.connect(g); g.connect(ctx.destination); o.start(t + dl); o.stop(t + dl + du + 0.02); })(notas[i][0], notas[i][1], notas[i][2]); } } catch(e){} };
  document.addEventListener('click', function(e) { try { var el = e.target && e.target.closest ? e.target.closest('button, .go') : null; if (el && !el.disabled) window.killaClick(); } catch(err){} });
  document.addEventListener('click', function(e) { try { var ov = document.getElementById('startOverlay'); if (ov && getComputedStyle(ov).display !== 'none') window.menuMusicStart(); } catch(err){} });
  var stack = [];
  var portadaEls = null;
  function portadaParts(){
    if (portadaEls) return portadaEls;
    var ov = document.getElementById('startOverlay');
    if (!ov) return [];
    var h1 = ov.querySelector('h1'), img = document.getElementById('coverImg'), h2 = ov.querySelector('h2'), logo = document.getElementById('lvrLogo'), btn = document.getElementById('uiBtnJugar');
    portadaEls = [h1, img, h2, logo, btn].filter(Boolean);
    return portadaEls;
  }
  function setPortadaVisible(v){
    portadaParts().forEach(function(e){ e.style.display = v ? '' : 'none'; });
  }
  function renderMisiones(){
    var box = document.getElementById('uiMisionesList');
    if (!box) return;
    try {
      if (typeof MISIONES === 'undefined' || typeof misionDisponible !== 'function') { box.innerHTML = '<p class="killaNote">Abre el menú de pausa en el juego para ver las misiones.</p>'; return; }
      var grupos = [['Taxi','taxi'],['Particular','particular'],['Bus','bus']];
      var vehIcons = {
        taxi: '<svg width="56" height="28" viewBox="0 0 64 32" aria-hidden="true"><path d="M4 24 L4 17 Q4 14 7 13 L12 12 L17 6 Q18 4 21 4 L38 4 Q41 4 43 6 L52 12 Q58 13 60 16 L60 22 Q60 24 58 24 L53 24 A6 6 0 0 0 41 24 L19 24 A6 6 0 0 0 7 24 Z" fill="#ffd54f" stroke="#0b2536" stroke-width="1.2"/><path d="M19 6 L27 6 L27 12 L15 12 Z" fill="#0b2536"/><path d="M29 6 L39 6 L44 12 L29 12 Z" fill="#0b2536"/><rect x="24" y="1" width="12" height="4" rx="1" fill="#ffd54f" stroke="#0b2536" stroke-width="0.8"/><rect x="14" y="19" width="34" height="2.4" fill="#0b2536"/><rect x="16" y="19" width="3" height="2.4" fill="#fff"/><rect x="22" y="19" width="3" height="2.4" fill="#fff"/><rect x="28" y="19" width="3" height="2.4" fill="#fff"/><rect x="34" y="19" width="3" height="2.4" fill="#fff"/><rect x="40" y="19" width="3" height="2.4" fill="#fff"/><circle cx="13" cy="24" r="5" fill="#000"/><circle cx="13" cy="24" r="2" fill="#cfd8dc"/><circle cx="47" cy="24" r="5" fill="#000"/><circle cx="47" cy="24" r="2" fill="#cfd8dc"/></svg>',
        particular: '<svg width="56" height="28" viewBox="0 0 64 32" aria-hidden="true"><path d="M4 24 L4 17 Q4 14 7 13 L12 12 L17 6 Q18 4 21 4 L38 4 Q41 4 43 6 L52 12 Q58 13 60 16 L60 22 Q60 24 58 24 L53 24 A6 6 0 0 0 41 24 L19 24 A6 6 0 0 0 7 24 Z" fill="#2196f3" stroke="#0b2536" stroke-width="1.2"/><path d="M19 6 L27 6 L27 12 L15 12 Z" fill="#0b2536"/><path d="M29 6 L39 6 L44 12 L29 12 Z" fill="#0b2536"/><rect x="14" y="16" width="36" height="2" fill="#0d47a1" opacity="0.6"/><circle cx="13" cy="24" r="5" fill="#000"/><circle cx="13" cy="24" r="2" fill="#cfd8dc"/><circle cx="47" cy="24" r="5" fill="#000"/><circle cx="47" cy="24" r="2" fill="#cfd8dc"/></svg>',
        bus: '<svg width="77" height="28" viewBox="0 0 88 32" aria-hidden="true"><path d="M3 26 L3 8 Q3 5 6 5 L78 5 Q83 5 84 9 L85 22 Q85 26 81 26 L76 26 A6 6 0 0 0 64 26 L22 26 A6 6 0 0 0 10 26 Z" fill="#fff" stroke="#0b2536" stroke-width="1.2"/><rect x="70" y="7" width="13" height="10" fill="#0b2536"/><rect x="8" y="8" width="9" height="8" fill="#0b2536"/><rect x="19" y="8" width="9" height="8" fill="#0b2536"/><rect x="30" y="8" width="9" height="8" fill="#0b2536"/><rect x="41" y="8" width="9" height="8" fill="#0b2536"/><rect x="52" y="8" width="9" height="8" fill="#0b2536"/><rect x="3" y="18" width="82" height="4" fill="#e11d2e"/><rect x="62" y="7" width="7" height="19" fill="none" stroke="#0b2536" stroke-width="1"/><circle cx="16" cy="26" r="5" fill="#000"/><circle cx="16" cy="26" r="2" fill="#cfd8dc"/><circle cx="70" cy="26" r="5" fill="#000"/><circle cx="70" cy="26" r="2" fill="#cfd8dc"/></svg>'
      };
      var h = '';
      grupos.forEach(function(g){
        var lista = MISIONES.filter(function(m){ return m.veh === g[1] && misionDisponible(m) && misionBest(m.id) < 3; });
        if (!lista.length) return;
        h += '<h3 style="margin:14px 0 2px"><span class="killaVehIcon">' + vehIcons[g[1]] + '</span>' + g[0] + '</h3>';
        lista.forEach(function(m){
          var best = (typeof misionBest === 'function') ? misionBest(m.id) : 0;
          var stars = '';
          for (var i=0;i<3;i++) stars += (i < best ? '★' : '☆');
          var btnClass = g[1] === 'taxi' ? 'killaBtnYl' : (g[1] === 'particular' ? 'killaBtnCy' : 'killaBtnRd');
          var btn = '';
          if (best > 0) btn = '<button class="' + btnClass + '" onclick="killaUIStartMision(\\'' + m.id + '\\')">REPETIR</button>';
          else btn = '<button class="' + btnClass + '" onclick="killaUIStartMision(\\'' + m.id + '\\')">JUGAR</button>';
          var tituloLimpio = (m.titulo || '').replace(/[\\u{1F300}-\\u{1FAFF}\\u{2600}-\\u{27BF}\\u{2B00}-\\u{2BFF}]/gu, '').trim();
          var descLimpia = (m.desc || '').replace(/[\\u{1F300}-\\u{1FAFF}\\u{2600}-\\u{27BF}\\u{2B00}-\\u{2BFF}]/gu, '').trim();
          h += '<div class="killaRow killaCard-' + g[1] + '"><div><h3>' + tituloLimpio + '</h3><p>' + descLimpia + '</p><p style="color:#ffd54f">' + stars + '</p></div>' + btn + '</div>';
        });
      });
      box.innerHTML = h || '<p class="killaNote">No hay misiones disponibles por ahora.</p>';
    } catch(e) { box.innerHTML = '<p class="killaNote">No se pudo cargar la lista de misiones.</p>'; }
  }
  function renderCircuitos(){
    var box = document.getElementById('uiCircuitos');
    if (!box) return;
    var desbloq = (typeof carreraDesbloqueada === 'function' && carreraDesbloqueada());
    if (!desbloq) {
      box.innerHTML = '<p class="killaNote">Se desbloquea al completar las 11 misiones nuevas con 3 estrellas.</p>';
      return;
    }
    var h = '';
    var lista = (typeof CIRCUITOS !== 'undefined') ? CIRCUITOS : [];
    for (var i = 0; i < lista.length; i++) {
      var c = lista[i];
      var clima = c.lluvia ? 'Con lluvia y arroyos' : 'En seco';
      h += '<div class="killaRow"><div><h3>' + c.nombre.toUpperCase() + '</h3><p>' + c.vueltas + ' vueltas · ' + clima + '</p></div>'
        + '<button class="killaBtnYl" data-circuito="' + c.id + '" onclick="killaUIStartCarreraCircuito(this)">JUGAR</button></div>';
    }
    box.innerHTML = h;
  }
  window.killaUIStartCarreraCircuito = function(btn){
    var cid = btn.getAttribute('data-circuito') || 'largo';
    killaUIStartCarrera(killaMultiVehGet(), cid);
  };
  var multiVehs = [
    { v: 'taxi', n: 'TAXI', img: 'vehiculos/killa-taxi.png' },
    { v: 'particular', n: 'PARTICULAR', img: 'vehiculos/killa-particular.png' },
    { v: 'bus', n: 'BUS', img: 'vehiculos/killa-bus.png' }
  ];
  var multiVehIdx = 0;
  window.killaMultiVehGet = function(){ return multiVehs[multiVehIdx].v; };
  window.killaMultiVehCambiar = function(d){
    multiVehIdx = (multiVehIdx + d + multiVehs.length) % multiVehs.length;
    var im = document.getElementById('killaMultiVehImg'), nm = document.getElementById('killaMultiVehNom');
    if (im) im.src = multiVehs[multiVehIdx].img;
    if (nm) nm.textContent = multiVehs[multiVehIdx].n;
  };
  window.actualizarRadioBar = function(){
    var rb = document.getElementById("radioBar");
    if (!rb) return;
    var ov = document.getElementById("startOverlay");
    var vis = false;
    if (ov) { vis = ov.style.display !== "none" && getComputedStyle(ov).display !== "none"; }
    rb.style.display = vis ? "none" : "";
  };

  /* Botón atrás del móvil (Rafael, 2026-10-29): con partida en curso muestra
     el diálogo de abandonar; si no, deja el comportamiento normal. */
  var killaGuardOn = false;
  /* Matices por vehículo en el área de control (Rafael, 2026-10-29): refleja
     S.vehicle en body[data-veh]; el CSS de hudfix tiñe sutilmente los acentos. */
  setInterval(function(){ try { var v = (typeof S !== "undefined" && S && S.vehicle) || null; if (!v && typeof CAR_CHOICE !== \"undefined") v = CAR_CHOICE === \"azul" ? \"particular" : (CAR_CHOICE === \"bus" ? \"bus" : \"taxi"); if (v && document.body.dataset.veh !== v) document.body.dataset.veh = v;\n    var pc = document.getElementById(\"consolaControles");\n    if (!pc) { pc = document.createElement(\"div"); pc.id = \"consolaControles"; document.body.appendChild(pc); }\n    var ov = document.getElementById(\"startOverlay");\n    pc.style.display = (ov && ov.style.display === \"none") ? \"block" : \"none";\n  } catch (e) {} }, 700);

  window.killaPushGuard = function(forzar){
    if (killaGuardOn && !forzar) return;
    try { history.pushState({ killaGuard: 1 }, ""); killaGuardOn = true; } catch (e) {}
  };
  function killaBackAsegurarDlg(){
    if (document.getElementById("backDialogPanel")) return;
    var bk = document.createElement("div");
    bk.id = "backDialogBack";
    bk.style.cssText = "position:fixed;inset:0;background:rgba(0,0,0,.55);display:none;z-index:1002";
    bk.onclick = function(){ window.killaBackCancel(); };
    var pn = document.createElement("div");
    pn.id = "backDialogPanel";
    pn.style.cssText = "position:fixed;left:50%;top:50%;transform:translate(-50%,-50%);width:min(320px,86vw);background:#fffbe8;color:#222;border:3px solid #22d3ee;border-radius:18px;padding:20px;text-align:center;display:none;z-index:1003;font-family:Titillium Web,Arial,sans-serif";
    pn.innerHTML = "<h2 id='backDialogTitulo' style='margin:0 0 6px;font-size:20px'>¿Abandonar misión?</h2>"
      + "<p style='margin:0 0 14px;font-size:14px'>Perderás el progreso de esta partida.</p>"
      + "<button onclick='killaBackConfirm()' style='display:block;width:100%;border:0;border-radius:12px;padding:12px;font-size:16px;font-weight:800;cursor:pointer;background:linear-gradient(180deg,#43a047,#2e7d32);color:#fff'>Sí, abandonar</button>"
      + "<button onclick='killaBackCancel()' style='display:block;width:100%;border:0;border-radius:12px;padding:12px;font-size:16px;font-weight:800;cursor:pointer;background:linear-gradient(180deg,#42a5f5,#1e88e5);color:#fff;margin-top:10px'>Seguir jugando</button>";
    document.body.appendChild(bk);
    document.body.appendChild(pn);
  }
  var killaBackDlgAbierto = false;
  window.killaBackMostrar = function(tipo){
    killaBackAsegurarDlg();
    var tit = document.getElementById("backDialogTitulo");
    if (tit) tit.textContent = tipo === "mision" ? "¿Abandonar misión?" : tipo === "carrera" ? "¿Abandonar carrera?" : "¿Abandonar partida?";
    document.getElementById("backDialogBack").style.display = "block";
    document.getElementById("backDialogPanel").style.display = "block";
    killaBackDlgAbierto = true;
  };
  window.killaBackOcultar = function(){
    var b = document.getElementById("backDialogBack"), p = document.getElementById("backDialogPanel");
    if (b) b.style.display = "none";
    if (p) p.style.display = "none";
    killaBackDlgAbierto = false;
  };
  window.killaBackCancel = function(){ window.killaBackOcultar(); };
  window.killaBackConfirm = function(){
    window.killaBackOcultar();
    killaGuardOn = false;
    try {
      if (typeof closePausa === "function") { var pp = document.getElementById("pausaPanel"); if (pp && pp.classList.contains("open")) closePausa(); }
      if (S && S.misionActiva) {
        S.misionActiva = null; S.misionProg = 0; S.misionSaltos = 0; S.misionTiempo = 0;
        S.mission = null;
        if (S.person) S.person.setVisible(false);
        if (S.ring) S.ring.setVisible(false);
        if (S.busRing) S.busRing.setVisible(false);
        if (S.rutaGps) S.rutaGps.clear();
        var tw = document.getElementById("timerWrap"); if (tw) tw.style.display = "none";
        if (typeof actualizarChip === "function") actualizarChip();
      }
      if (S && S.carreraActiva && typeof cancelarCarrera === "function") cancelarCarrera();
      if (S && S.multiActiva && typeof cancelarMulti === "function") cancelarMulti();
      try { if (typeof stopRadio === "function") stopRadio(); } catch (e) {}
      // Al abandonar: quitar TODO efecto de sonido del juego (Rafael 2026-10-30)
      try { if (typeof ENG !== "undefined" && ENG && ENG.gain && ENG.ctx) ENG.gain.gain.setTargetAtTime(0, ENG.ctx.currentTime, 0.05); } catch (e) {}
      try { if (S && S.busEl && !S.busEl.paused) { S.busEl.pause(); S.busEl.volume = 0; } } catch (e) {}
      try { if (typeof SFX_EL !== "undefined") for (var _sk in SFX_EL) { try { var _sa = SFX_EL[_sk]; if (_sa) { _sa.pause(); _sa.currentTime = 0; } } catch (e2) {} } } catch (e) {}
      try { if (typeof rainAudio === "function") rainAudio(0); } catch (e) {}
      try { if (S) S.started = false; } catch (e) {}
      try { if (window.menuMusicStart) window.menuMusicStart(); } catch (e) {}
    } catch (e) {}
    var ov2 = document.getElementById("startOverlay");
    if (ov2) ov2.style.display = "";
    window.killaUIShow("modo");
  };
  window.addEventListener("popstate", function(){
    var enJuego = false, tipo = "";
    try {
      if (S && S.misionActiva) { enJuego = true; tipo = "mision"; }
      else if (S && S.carreraActiva) { enJuego = true; tipo = "carrera"; }
      else if (S && S.multiActiva) { enJuego = true; tipo = "multi"; }
    } catch (e) {}
    if (killaBackDlgAbierto) { window.killaPushGuard(true); return; }
    var pausaAbierta = false;
    try { var pp2 = document.getElementById("pausaPanel"); pausaAbierta = pp2 && pp2.classList.contains("open"); } catch (e) {}
    if (pausaAbierta) { try { closePausa(); } catch (e) {} window.killaPushGuard(true); return; }
    if (enJuego) { window.killaBackMostrar(tipo); window.killaPushGuard(true); return; }
    killaGuardOn = false;
  });
  window.killaUIShow = function(vista){
    var ov = document.getElementById('startOverlay');
    if (!ov) return;
    var cur = window.killaUIVista || 'portada';
    if (vista !== cur) stack.push(cur);
    window.killaUIVista = vista;
    try { window.menuMusicStart(); } catch(e) {}
    ['uiModo','uiMisiones','uiMulti'].forEach(function(id){ var e = document.getElementById(id); if (e) e.style.display = 'none'; });
    if (vista === 'portada') { setPortadaVisible(true); window.actualizarRadioBar(); return; }
    setPortadaVisible(false);
    if (vista === 'misiones') renderMisiones();
    if (vista === 'multi') renderCircuitos();
    var target = document.getElementById(vista === 'modo' ? 'uiModo' : vista === 'misiones' ? 'uiMisiones' : 'uiMulti');
    if (target) target.style.display = 'block';
    ov.scrollTop = 0;
    window.actualizarRadioBar();
  };
  window.killaUIStartMision = function(id){
    try { window.menuMusicStop(); } catch(e) {}
    var ov = document.getElementById('startOverlay');
    if (ov) ov.style.display = 'none';
    window.actualizarRadioBar();
    window.killaPushGuard();
    try { if (typeof startGame === 'function') startGame(); } catch(e) {}
    setTimeout(function(){ try { if (typeof startMision === 'function') startMision(id); } catch(e) {} }, 100);
  };
  window.killaUIStartCarrera = function(veh, circuito){
    try { window.menuMusicStop(); } catch(e) {}
    var ov = document.getElementById('startOverlay');
    if (ov) ov.style.display = 'none';
    window.actualizarRadioBar();
    window.killaPushGuard();
    try { if (typeof startGame === 'function') startGame(); } catch(e) {}
    setTimeout(function(){ try { if (typeof startCarrera === 'function') startCarrera(veh, circuito); } catch(e) {} }, 100);
  };
  window.killaUIStartMulti = function(modo, veh){
    try { window.menuMusicStop(); } catch(e) {}
    var ov = document.getElementById('startOverlay');
    if (ov) ov.style.display = 'none';
    window.actualizarRadioBar();
    window.killaPushGuard();
    try { if (typeof startGame === 'function') startGame(); } catch(e) {}
    setTimeout(function(){ try { if (typeof startMulti === 'function') startMulti(modo, veh); } catch(e) {} }, 100);
  };
  // Botón JUGAR de la portada (el .go original ya no existe; este es el nuevo)
  document.addEventListener('click', function(e){
    if (e.target && e.target.id === 'uiBtnJugar') { e.stopPropagation(); window.killaUIShow('modo'); }
  });
})();
</script>
"""
rep("</script>\n</body>\n</html>", "</script>\n" + _UI_JS + "</body>\n</html>")
# ===== SPLASH LVR GAMES AL INICIO (Rafael, 2026-10-28, cambio 1) =====
# Flujo nuevo, uno a uno: al entrar al juego NO se muestra la portada antes.
# Primero sale el logo LVR (incrustado, sin esperar red) mientras carga el video;
# en cuanto el video puede reproducirse, sale el video; al terminar o al tocarlo,
# sale la portada con JUGAR. Nunca: portada -> negro -> video -> portada.
# La portada arranca oculta (display:none) y solo se muestra al terminar el splash.
rep('<div id="startOverlay">', '<div id="startOverlay" style="display:none">')
_SPLASH_HTML = """
<div id="lvrSplash" style="position:fixed;inset:0;z-index:999;background:#000;transition:opacity .5s ease">
  <img id="lvrSplashLogo" alt="Las vainas del Rafa" src='""" + _webp64('/home/hatch/workspace/goals/killa-drivers/files/splash-inicio-las-vainas-9x16-anime-gamer-3-letra-2.webp') + """' style="position:absolute;inset:0;display:block;width:100%;height:100%;object-fit:contain;background:#000;transition:opacity .8s ease">
  <video id="lvrSplashVideo" src="splash-lvr.mp4" playsinline preload="auto" style="position:absolute;inset:0;display:none;width:100%;height:100%;object-fit:contain;background:#000;opacity:0;transition:opacity .8s ease"></video>
</div>
<script>
(function(){
  var s = document.getElementById('lvrSplash');
  if (!s) return;
  var v = document.getElementById('lvrSplashVideo');
  var logo = document.getElementById('lvrSplashLogo');
  var ov = document.getElementById('startOverlay');
  var done = false, fading = false, playing = false, safetyTimer = null;
  function showCover(){
    if (done) return; done = true;
    if (safetyTimer) clearTimeout(safetyTimer);
    try { v.pause(); } catch(e) {}
    var ov2 = document.getElementById('startOverlay');
    if (ov2) { try { ov2.style.setProperty('display','flex','important'); } catch(e) { ov2.style.display = 'flex'; } }
    s.style.opacity = '0';
    setTimeout(function(){
      try { s.style.setProperty('display','none','important'); } catch(e) { s.style.display = 'none'; }
    }, 500);
  }
  function fadeToVideo(){
    if (done || fading) return; fading = true; playing = true;
    if (safetyTimer) clearTimeout(safetyTimer);
    if (v) v.style.display = 'block';
    requestAnimationFrame(function(){ if (v) v.style.opacity = '1'; if (logo) logo.style.opacity = '0'; });
    setTimeout(function(){ if (logo) logo.style.display = 'none'; }, 850);
  }
  function tryPlaySound(){
    if (done) return;
    try { v.muted = false; v.volume = 1; } catch(e) {}
    try {
      var pr = v.play();
      if (pr && pr.then) pr.then(function(){ fadeToVideo(); }).catch(function(){
        try { v.muted = true; var pr2 = v.play(); if (pr2 && pr2.then) pr2.then(fadeToVideo); else fadeToVideo(); } catch(e){ fadeToVideo(); }
      });
      else fadeToVideo();
    } catch(e) { fadeToVideo(); }
  }
  if (v) {
    v.addEventListener('ended', showCover);
    v.addEventListener('playing', fadeToVideo);
    v.addEventListener('canplay', tryPlaySound);
    if (v.readyState >= 3) tryPlaySound();
    try { v.load(); } catch(e) {}
  }
  safetyTimer = setTimeout(function(){ if (!playing) showCover(); }, 60000); // Seguridad: solo si el video nunca arrancó en 60 s; si está sonando, se cancela al arrancar y termina solo
})();
</script>
"""
rep('<div id="startOverlay" style="display:none">', _SPLASH_HTML + '<div id="startOverlay" style="display:none">')
# Pausa: sin emojis en los encabezados de misiones (solo la cáscara, la lógica no cambia)
rep("🎯 MISIONES", "MISIONES")
rep("['🚖 Taxi', 'taxi'], ['🚗 Particular', 'particular'], ['🚌 Bus', 'bus']", "['Taxi', 'taxi'], ['Particular', 'particular'], ['Bus', 'bus']")

# Volante giratorio en vez del stick (Rafael, 2026-10-29): mismo tacto
# (eje X = dirección, tirar abajo = freno); el SVG gira con la dirección.
_VOLANTE_SVG = "<svg id=\"volante\" viewBox=\"0 0 120 120\"><defs><radialGradient id=\"vgrad\" cx=\"38%\" cy=\"32%\" r=\"80%\"><stop offset=\"0%\" stop-color=\"#5a6b7a\"/><stop offset=\"72%\" stop-color=\"#26313b\"/></radialGradient></defs><circle cx=\"60\" cy=\"60\" r=\"52\" fill=\"none\" stroke=\"url(#vgrad)\" stroke-width=\"13\"/><circle cx=\"60\" cy=\"60\" r=\"52\" fill=\"none\" class=\"vac\" stroke-width=\"3\" stroke-dasharray=\"10 8\" opacity=\"0.9\"/><g stroke=\"#5b6f85\" stroke-width=\"12\" stroke-linecap=\"round\"><line x1=\"60\" y1=\"60\" x2=\"60\" y2=\"16\"/><line x1=\"60\" y1=\"60\" x2=\"21\" y2=\"82\"/><line x1=\"60\" y1=\"60\" x2=\"99\" y2=\"82\"/></g><circle cx=\"60\" cy=\"60\" r=\"15\" fill=\"#141d29\" class=\"vac\" stroke-width=\"3\"/><rect x=\"56\" y=\"2\" width=\"8\" height=\"12\" rx=\"3\" class=\"fac\"/></svg>"
rep("<div id=\"joy\"><div id=\"joyRing\"></div><div id=\"joyKnob\">✥</div></div>",
    "<div id=\"joy\"><div id=\"joyRing\"></div>" + _VOLANTE_SVG + "<div id=\"joyKnob\">✥</div></div>")
rep("const setKnob = (dx, dy) => { knob.style.transform = 'translate(calc(-50% + ' + dx + 'px), calc(-50% + ' + dy + 'px))'; };",
    "const setKnob = (dx, dy) => { knob.style.transform = 'translate(calc(-50% + ' + dx + 'px), calc(-50% + ' + dy + 'px))'; var _vw = document.getElementById('volante'); if (_vw) _vw.style.transform = 'rotate(' + Math.round(dx / 42 * 135) + 'deg)'; };")
# Sensibilidad del volante un poco más baja (Rafael, 2026-10-29): factor 0.8 en la dirección táctil.
rep("S.touch.steer = Math.abs(nx) < 0.12 ? 0 : nx;",
    "S.touch.steer = Math.abs(nx) < 0.12 ? 0 : nx * 0.8;")
rep("    S.scene.cameras.main.shake(90, 0.004);",
    "    addTrauma(speed > 400 ? 0.7 : 0.45); if (speed > 350) hitStop(70);")

rep("  cam.rotation += rotDiff * Math.min(1, dt * 5.0); // acercamiento exponencial: giro suave, sin tir\u00f3n",
    "  cam.rotation += rotDiff * Math.min(1, dt * 5.0); // acercamiento exponencial: giro suave, sin tir\u00f3n\n  updateTrauma(dt);")

rep("function misionCompletada(m) {",
    "function misionCompletada(m) {\n  try { if (typeof addTrauma === \"function\") addTrauma(0.6); } catch (e) {}")
open('new.html', 'w').write(s)
print("parches OK, largo final:", len(s))
