// Ajustes de Wither para CUNICULUM:
// - evita jaulas de obsidiana y bloques duros alrededor del Wither;
// - lo empuja hacia abajo si se aleja demasiado del combate vertical.
function cuniwitherSafePlayerName(player) {
  var name = '';
  try { name = String(player.username || player.name || ''); } catch (ignoredName) { }
  return name.replace(/[^A-Za-z0-9_]/g, '');
}

function cuniwitherRunNearPlayer(server, playerName, command) {
  if (!server || !playerName) {
    return;
  }
  server.runCommandSilent('execute at ' + playerName + ' as @e[type=minecraft:wither,distance=..96] at @s run ' + command);
}

PlayerEvents.tick(function (event) {
  var player = event.player;
  var server = event.server;
  if (!player || !server) {
    return;
  }

  var age = 0;
  try { age = Number(player.age || 0); } catch (ignoredAge) { age = 0; }
  if (age % 80 !== 0) {
    return;
  }

  var name = cuniwitherSafePlayerName(player);
  if (!name) {
    return;
  }

  var cageBlocks = [
    'minecraft:obsidian',
    'minecraft:crying_obsidian',
    'minecraft:reinforced_deepslate',
    'minecraft:ancient_debris',
    'minecraft:netherite_block',
    'minecraft:iron_bars',
    'minecraft:deepslate',
    'minecraft:stone',
    'minecraft:cobbled_deepslate'
  ];

  for (var i = 0; i < cageBlocks.length; i++) {
    cuniwitherRunNearPlayer(
      server,
      name,
      'fill ~-2 ~-1 ~-2 ~2 ~3 ~2 minecraft:air replace ' + cageBlocks[i]
    );
  }

  server.runCommandSilent(
    'execute at ' + name + ' as @e[type=minecraft:wither,distance=48..96] at @s run tp @s ~ ~-8 ~'
  );
});
