import * as SERVER from '@minecraft/server';
import "./item_consume.js";
import "./debug_xaier.js";
import "./laboratorio.js";
import "./loots_block.js";
import "./generate_old_sistem.js";
import "./events_block.js";
import "./events_items.js";


world.afterEvents.entityDie.subscribe(event => {
  const entity = event.deadEntity;
  if (entity.typeId === "xaierg:rotten_sembrador") {
    if (Math.random() < 0.5) {
      // Usa la lógica de forEachNearbyPlayer para jugadores a 32 bloques
      entity.dimension.getEntities({ location: entity.location, maxDistance: 32 }).forEach(e => {
        if (e.typeId === 'minecraft:player') {
          entity.dimension.getPlayers().forEach(player => {
            player.runCommand(
              `execute positioned ${entity.location.x} ${entity.location.y} ${entity.location.z} run `
            );
            // Cambia el comando "say ..." por el que necesites
          });
        }
      });
    }
  }
});


//call cordy
registerCustomComponent('xaierg:call_cordy', {
  onStepOn: e => {
    if (e.entity && e.entity.typeId === "minecraft:player") {
      // Solo ejecuta si es un jugador
      forEachNearbyPlayer(e.block, 3, (player, block) => {
        player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run function call_cordy`);
      });
    }
  }
});


//level_health.js
import { world } from "@minecraft/server";

const healthLevels = [
  { item: "xaierg:level_health1", level: 1, event: "xaierg:add_health1" },
  { item: "xaierg:level_health2", level: 2, event: "xaierg:add_health2" },
  { item: "xaierg:level_health3", level: 3, event: "xaierg:add_health3" },
  { item: "xaierg:level_health4", level: 4, event: "xaierg:add_health4" },
  { item: "xaierg:level_health5", level: 5, event: "xaierg:add_health5" },
  { item: "xaierg:level_health6", level: 6, event: "xaierg:add_health6" },
  { item: "xaierg:level_health7", level: 7, event: "xaierg:add_health7" },
  { item: "xaierg:level_health8", level: 8, event: "xaierg:add_health8" },
  { item: "xaierg:level_health9", level: 9, event: "xaierg:add_health9" },
  { item: "xaierg:level_health10", level: 10, event: "xaierg:add_health10" }
];

world.afterEvents.itemCompleteUse.subscribe(event => {
  const { itemStack, source } = event;
  if (source.typeId !== "minecraft:player") return;
  const health = healthLevels.find(h => h.item === itemStack.typeId);
  if (health) {
    // Guarda el nivel actual en una propiedad dinámica
    source.setDynamicProperty("healthLevel", health.level);
    source.runCommand(`particle xaierg:emerge_cordy ~~~`);
    source.runCommand(`event entity @s ${health.event}`);
  }
});



// Helper for registering block components
function registerCustomComponent(id, handlers) {
  SERVER.world.beforeEvents.worldInitialize.subscribe(initEvent => {
    initEvent.blockComponentRegistry.registerCustomComponent(id, handlers);
  });
}

// Helper to run a command for every nearby player within maxDistance
function forEachNearbyPlayer(block, maxDistance, commandCallback) {
  block.dimension.getEntities({ location: block.location, maxDistance })
    .forEach(entity => {
      if (entity.typeId === 'minecraft:player') {
        block.dimension.getPlayers().forEach(player => {
          commandCallback(player, block);
        });
      }
    });
}

// cordyceps_venenosoX
registerCustomComponent('xaierg:cordyceps_venenosoX', {
  onTick: e => {
    e.block.dimension.getEntities({ location: e.block.location, maxDistance: 32 }).forEach(entity => {
      if (entity.typeId === 'minecraft:player') {
        e.block.setType('minecraft:air');
      }
    });
  },
  onStepOn: e => {
    forEachNearbyPlayer(e.block, 32, (_player, block) => {
      // Preserve original behavior, but just air out the block on tick and step on
      // No player-specific logic here except clearing block
      // Original code removed getPlayers loop on step on for setType - unified approach
      block.setType('minecraft:air');
    });
  }
});

// meta_cordycepsX
registerCustomComponent('xaierg:meta_cordycepsX', {
  onTick: e => {
    forEachNearbyPlayer(e.block, 32, (player, block) => {
      player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run function met`);
      block.setType('minecraft:air');
    });
  }
});

// cordyceps_tocon1X
registerCustomComponent('xaierg:cordyceps_tocon1X', {
  onPlayerInteract: e => {
    e.block.setType('xaierg:cordyceps');
  }
});

// tocon_cleawerX
registerCustomComponent('xaierg:tocon_cleawerX', {
  onTick: e => {
    forEachNearbyPlayer(e.block, 32, (player, block) => {
      player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run function spawn_cleawer`);
      block.setType('xaierg:cordyceps');
    });
  }
});

// mob_toconX
registerCustomComponent('xaierg:mob_toconX', {
  onRandomTick: e => {
    const nido = [
      ...Array(40).fill('function spawn_tocon'),
      ...Array(20).fill('setblock xaierg:cordyceps_spore2'),
      ...Array(10).fill('setblock xaierg:cordyceps'),
      'structure load nido_cordyceps3 ~-6~~-6',
      'structure load nido_cordyceps2 ~-6~~-6',
      'structure load nido_cordyceps ~-6~~-6',
      'function spawn_tocon'
    ];
    const randomNido = nido[Math.floor(Math.random() * nido.length)];
    forEachNearbyPlayer(e.block, 20, (player, block) => {
      player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run ${randomNido}`);
    });
  }
});

// summon_shamblerX
registerCustomComponent('xaierg:summon_shamblerX', {
  onStepOn: e => {
    e.block.setType('xaierg:cordyceps'); // single fixed type, so no random needed
    forEachNearbyPlayer(e.block, 3, (player, block) => {
      player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run function spawn_shambler`);
    });
    // Kill enderman entities near block as original code
    e.block.dimension.getEntities({ location: e.block.location, maxDistance: 3 }).forEach(entity => {
      if (entity.typeId === 'minecraft:enderman') {
        entity.kill();
      }
    });
  }
});

// summon_sowerX
registerCustomComponent('xaierg:summon_sowerX', {
  onTick: e => {
    const sowers = ['function summon_sembrador', 'function summon_sembrador', 'function summon_rotten_sembrador'];
    const randomSower = sowers[Math.floor(Math.random() * sowers.length)];
    forEachNearbyPlayer(e.block, 32, (player, block) => {
      player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run ${randomSower}`);
    });
  }
});

// summon_emerge_mutedX
registerCustomComponent('xaierg:summon_emerge_mutedX', {
  onTick: e => {
    forEachNearbyPlayer(e.block, 32, (player, block) => {
      player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run function muted_emerge`);
      block.setType('xaierg:cordyceps');
    });
  }
});

// summon_bloaterX
registerCustomComponent('xaierg:summon_bloaterX', {
  onStepOn: e => {
    forEachNearbyPlayer(e.block, 3, (player, block) => {
      player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run function spawn_bloater`);
    });
  },
  onTick: e => {
    // same as onRandomTick in original but single function call added
    forEachNearbyPlayer(e.block, 3, (player, block) => {
      player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run function spawn_bloater`);
    });
  },
  onRandomTick: e => {
    forEachNearbyPlayer(e.block, 3, (player, block) => {
      player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run function spawn_bloater`);
    });
  }
});

// cordyceps_layer
registerCustomComponent('xaierg:cordyceps_layer', {
  onTick: e => {
    const blockTypesv = ['xaierg:cordyceps_layer1', 'xaierg:cordyceps_layer2', 'xaierg:cordyceps_layer3', 'xaierg:cordyceps_layer4', 'xaierg:cordyceps_layer5'];
    const randomBlockType = blockTypesv[Math.floor(Math.random() * blockTypesv.length)];
    forEachNearbyPlayer(e.block, 32, (player, block) => {
      player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run setblock ~~~ ${randomBlockType}`);
            block.below(1).setType("xaierg:cordyceps_tocon1");
    });
  },
  onPlayerDestroy: e => {
    // Could reuse onTick if needed, currently no extra code
  },
  onPlayerInteract: e => {
    forEachNearbyPlayer(e.block, 32, (player, block) => {
      player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run particle xaierg:spore_p ${block.location.x} ${block.location.y} ${block.location.z}`);
    });
  }
});

// propagation cordyceps (tocon_tree)

registerCustomComponent('xaierg:tocon_tree', {
  onRandomTick: e => toconTree(e.block),
  onPlayerDestroy: e => toconTree(e.block),
  onPlayerInteract: e => {
    e.block.setType('xaierg:cordyceps_tocon1');
  },
  onStepOn: e => {null}
});

function getDistanceToAir(block, direction, maxDistance = 1) {
  let current = block;
  for (let i = 1; i <= maxDistance; i++) {
    switch (direction) {
      case 'up': current = current.above(1); break;
      case 'down': current = current.below(1); break;
      case 'north': current = current.north(1); break;
      case 'south': current = current.south(1); break;
      case 'east': current = current.east(1); break;
      case 'west': current = current.west(1); break;
    }
    if (!current) break;
    // Considera aire o agua como superficie
    if (current.isAir || current.typeId === 'minecraft:water' || current.typeId === 'minecraft:flowing_water' || current.typeId === 'minecraft:lava'|| current.typeId === 'minecraft:flowing_lava') return i; // <--- CAMBIO AQUÍ
  }
  return maxDistance + 1;
}

function isNearSurface(block, maxDistance = 3) {
  const directions = ['up', 'down', 'north', 'south', 'east', 'west'];
  return directions.some(dir => getDistanceToAir(block, dir, maxDistance) <= maxDistance);
}

function toconTree(block) {
  // Limitar propagación a 8 bloques de cualquier superficie de aire
  if (!isNearSurface(block, 3)) {
    block.setType('xaierg:cordyceps_tocon1');
    return;
  }

  const blockTypes = ['xaierg:cordy', 'xaierg:cordy', 'xaierg:cordyceps', 'xaierg:cordyceps_tocon1', 'xaierg:cordyceps_pre', 'xaierg:cordy', 'xaierg:cordy'];
  const randomBlockType = blockTypes[Math.floor(Math.random() * blockTypes.length)];

  const adjacentBlocks = [block.above(1), block.below(1), block.north(1), block.east(1), block.south(1), block.west(1)];
  const adjacentBlocks2 = [block.above(1)];

  const chanceToSpreadDown = 0.05;

  adjacentBlocks2.forEach(adjacentBlock => {
    if (adjacentBlock && adjacentBlock.isAir) {
      block.dimension.getEntities({ location: block.location, maxDistance: 12 }).forEach(entity => {
        if (entity.typeId === 'minecraft:player') {
          block.dimension.getPlayers().forEach(player => {
            player.runCommand(Math.random() < 0.5
              ? `execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run particle xaierg:knockback_spore ~ ~1 ~`
              : `playsound cordy.gen @a[r=16]`);
          });
        }
        
      });
    }
  });
const sides = [
  block.north(1),
  block.east(1),
  block.south(1),
  block.west(1)
];

const requiredTypes = ['xaierg:cordyceps_tocon1', 'xaierg:cordyceps', 'xaierg:cordy','xaierg:cordyceps_spore', 'xaierg:cordyceps_spore2','xaierg:flor1', 'xaierg:flor2',
      'xaierg:flor3', 'xaierg:flor4', 'xaierg:flor5', 'xaierg:flor6', 'xaierg:flor7', 'xaierg:cordyceps_layer1',
      'xaierg:cordyceps_layer2', 'xaierg:cordyceps_layer3', 'xaierg:cordyceps_layer4', 'xaierg:cordyceps_layer5'];

// Verifica que los 4 lados NO sean aire y sean del tipo requerido
const allSidesMatch = sides.every(adjacentBlock =>
  adjacentBlock &&
  !adjacentBlock.isAir &&
  requiredTypes.includes(adjacentBlock.typeId)
);

if (allSidesMatch) {
  block.setType('xaierg:cordyceps_tocon1');
}
const sides2 = [
  block.above(1), block.below(1)
];
const requiredTypes2 = ['xaierg:cordyceps_tocon1', 'xaierg:cordyceps', 'xaierg:cordy','xaierg:cordyceps_spore', 'xaierg:cordyceps_spore2','xaierg:flor1', 'xaierg:flor2',
      'xaierg:flor3', 'xaierg:flor4', 'xaierg:flor5', 'xaierg:flor6', 'xaierg:flor7', 'xaierg:cordyceps_layer1',
      'xaierg:cordyceps_layer2', 'xaierg:cordyceps_layer3', 'xaierg:cordyceps_layer4', 'xaierg:cordyceps_layer5'];
const allSidesMatch2 = sides2.every(adjacentBlock =>
  adjacentBlock &&
  !adjacentBlock.isAir &&
  requiredTypes2.includes(adjacentBlock.typeId)
);

if (allSidesMatch2) {
  block.setType('xaierg:cordyceps_tocon1');
}
  adjacentBlocks.forEach(adjacentBlock => {
    if (adjacentBlock && !adjacentBlock.isAir && ![
      'xaierg:cordyceps_dead', 'xaierg:cordyceps', 'minecraft:water', 'minecraft:flowing_water', 'minecraft:flowing_lava', 'minecraft:lava', 'xaierg:flor1', 'xaierg:flor2',
      'xaierg:flor3', 'xaierg:flor4', 'xaierg:flor5', 'xaierg:flor6', 'xaierg:flor7', 'xaierg:cordyceps_layer1',
      'xaierg:cordyceps_layer2', 'xaierg:cordyceps_layer3', 'xaierg:cordyceps_layer4', 'xaierg:cordyceps_layer5',
      'xaierg:cordyceps_spore', 'xaierg:cordyceps_spore2', 'xaierg:spawn_bloater', 'xaierg:summon_bloater', 'xaierg:summon_emerge_muted', 'xaierg:summon_sower',
      'xaierg:summon_shambler', 'xaierg:mob_tocon', 'xaierg:tocon_cleawer', 'xaierg:cordyceps_tocon1',
      'xaierg:meta_cordyceps', 'xaierg:cordyceps_pre', 'xaierg:cordyceps_structure'
    ].includes(adjacentBlock.typeId)) {
      if (adjacentBlock.location.y < block.location.y) { 
        if (Math.random() < chanceToSpreadDown) {
          adjacentBlock.setType(Math.random() < 0.55 ? randomBlockType : 'xaierg:cordy');
          block.setType('xaierg:cordyceps');
        }
      } else {
        adjacentBlock.setType(Math.random() < 0.5 ? randomBlockType : 'xaierg:cordy');
      }
    }
  });
}

// ...existing code...
// limpiadorX
registerCustomComponent('xaierg:limpiadorX', {
  onTick: e => {

    const limpiadorFuncs = ['function cat3', 'function cat3', 'function cat2', 'function cat1', 'function cat4'];
    const limpiador = limpiadorFuncs[Math.floor(Math.random() * limpiadorFuncs.length)];
    forEachNearbyPlayer(e.block, 32, (player, block) => {
      player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run ${limpiador}`);
    });

    // --- Generar estructuras en dos anillos ---
    const center = e.block.location;
    const structure_if = [
      'flower:infect_cordy1', 'flower:infect_cordy2'
    ];
    const probabilidad = 0.00025;
    const world = e.block.dimension;

    // Radios de los dos anillos
    const radius1 = 16;
    const radius2 = Math.floor(Math.random() * (40 - 35 + 1)) + 35;

    // Función para generar un anillo
    function generarAnillo(radius, step = 20) {
  for (let angle = 0; angle < 360; angle += step) {
        const rad = angle * Math.PI / 180;
        const x = Math.round(center.x + radius * Math.cos(rad));
        const z = Math.round(center.z + radius * Math.sin(rad));
        let y = center.y;

        // Busca la superficie hacia abajo (máx 12 bloques)
        let foundSurface = false;
        for (let dy = 0; dy < 12; dy++) {
          const blockBelow = world.getBlock({ x, y: y - dy, z });
          const blockAbove = world.getBlock({ x, y: y - dy + 1, z });
          if (
            blockBelow && blockAbove &&
            !blockBelow.isAir && blockAbove.isAir
          ) {
            y = y - dy + 1;
            foundSurface = true;
            break;
          }
        }

        if (foundSurface && Math.random() < probabilidad) {
          const estructura = structure_if[Math.floor(Math.random() * structure_if.length)];
          e.block.dimension.runCommand(
            `execute positioned ${x} ${y} ${z} run structure load ${estructura} ~~-5~`
          );
        }
      }
    }

   // Para el muro de anillo:
generarAnillo(radius1, 10); // Más denso, tipo muro
generarAnillo(radius2, 20); // El segundo anillo como antes
    // --- FIN NUEVO ---
  }
});

// propagation organismo cordyceps (toconTreeGen)
registerCustomComponent('xaierg:cordyceps_preX', {
  onRandomTick: e => toconTreeGen(e.block),
  onPlayerDestroy: e => toconTreeGen(e.block),
  onPlayerInteract: e => {
    toconTreeGen(e.block);
    e.player.runCommand(`execute positioned ${e.block.location.x} ${e.block.location.y} ${e.block.location.z} run particle xaierg:spore_p ${e.block.location.x} ${e.block.location.y} ${e.block.location.z}`);
  }
});

function toconTreeGen(block) {
  const blockTypesv = ['xaierg:flor1', 'xaierg:flor2', 'xaierg:flor3', 'xaierg:flor4', 'xaierg:flor5', 'xaierg:flor6', 'xaierg:flor7', 'xaierg:cordyceps_layer'];
  const randomBlockType = blockTypesv[Math.floor(Math.random() * blockTypesv.length)];

  const adjacentBlocks1 = [block.above(1), block.north(1), block.east(1), block.south(1), block.west(1)];
  const adjacentBlocks2 = [block.above(1)];

  adjacentBlocks1.forEach(adjacentBlock => {
    if (adjacentBlock && adjacentBlock.isAir) {
      adjacentBlock.setType(randomBlockType);
    }
  });

  const genCordyceps = [
    ...Array(25).fill('xaierg:cordyceps_structure'),
    ...Array(4).fill('xaierg:cordyceps_spore'),
    'xaierg:summon_bloater',
    'xaierg:summon_shambler',
    'xaierg:cordyceps',
    'xaierg:cordyceps_spore'
  ];
  const randomgenCordyceps = genCordyceps[Math.floor(Math.random() * genCordyceps.length)];
  block.setType(randomgenCordyceps);

  const Infected = [
    { id: 'xaierg:multi_infected', weight: 50 },
    { id: 'xaierg:multi_stalker', weight: 20 },
    { id: 'xaierg:clicker', weight: 50 },
    { id: 'xaierg:stalker', weight: 10 },
    { id: 'xaierg:child_clicker', weight: 10 },
    { id: 'xaierg:rotten_bloater', weight: 10 },
    { id: 'xaierg:tocon', weight: 1 }
  ];
  
  function weightedRandom(array) {
    const total = array.reduce((sum, item) => sum + item.weight, 0);
    let rand = Math.random() * total;
    for (const item of array) {
      if (rand < item.weight) return item.id;
      rand -= item.weight;
    }
  }
  
  // Uso:
  const randomInfected = weightedRandom(Infected);
  const genppc = ['ppc1', 'ppc2', 'ppc3', 'ppc4', 'ppc5', 'pilar3','ppc1', 'ppc2', 'ppc3', 'ppc4', 'ppc5', 'pilar3', 'pilar4', 'pilar5'];
  const ppc = genppc[Math.floor(Math.random() * genppc.length)];

  adjacentBlocks2.forEach(adjacentBlock => {
    if (adjacentBlock && ['minecraft:air', 'xaierg:flor1', 'xaierg:flor2', 'xaierg:flor3', 'xaierg:flor4', 'xaierg:flor5', 'xaierg:flor6', 'xaierg:flor7', 'xaierg:cordyceps_spore'].includes(adjacentBlock.typeId)) {
      block.dimension.getEntities({ location: block.location, maxDistance: 12 }).forEach(entity => {
        if (entity.typeId === 'minecraft:player') {
          block.dimension.getPlayers().forEach(player => {
            player.runCommand(Math.random() < 0.7
              ? `execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run structure load ${ppc} ~-1~~-1`
              : `execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run summon ${randomInfected} ~~3~`);
          });
        }
      });
    }
  });

  adjacentBlocks2.forEach(adjacentBlock => {
    if (adjacentBlock && ['minecraft:air', 'xaierg:flor1', 'xaierg:flor2', 'xaierg:flor3', 'xaierg:flor4', 'xaierg:flor5', 'xaierg:flor6', 'xaierg:flor7', 'xaierg:cordyceps_spore', 'xaierg:cordyceps_layer1', 'xaierg:cordyceps_layer2', 'xaierg:cordyceps_layer3', 'xaierg:cordyceps_layer4', 'xaierg:cordyceps_layer5'].includes(adjacentBlock.typeId)) {
      block.dimension.getEntities({ location: block.location, maxDistance: 20 }).forEach(entity => {
        if (entity.typeId === 'minecraft:player') {
         block.dimension.getPlayers().forEach(player => {
  const mode = player.getGameMode();
 if (mode === "creative" || mode === "spectator") return;
  player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run function spore_c`);

});
        }
      });
    }
  });
}

// spores
registerCustomComponent('xaierg:spores', {
  onTick: e => spores(e.block),
  onPlayerDestroy: e => spores(e.block)
});

function spores(block) {

  const genspore = ['xaierg:cordyceps_spore', 'xaierg:cordyceps_spore2'];
  const randomgenspore = genspore[Math.floor(Math.random() * genspore.length)];
  const adjacentBlocks2 = [block.above(1)];

 adjacentBlocks2.forEach(adjacentBlock => {
  if (
    adjacentBlock &&
    [
      'minecraft:air',
      'xaierg:flor1',
      'xaierg:flor2',
      'xaierg:flor3',
      'xaierg:flor4',
      'xaierg:flor5',
      'xaierg:flor6',
      'xaierg:flor7',
      'xaierg:cordyceps_spore',
      'xaierg:cordyceps_layer1',
      'xaierg:cordyceps_layer2',
      'xaierg:cordyceps_layer3',
      'xaierg:cordyceps_layer4',
      'xaierg:cordyceps_layer5'
    ].includes(adjacentBlock.typeId)
  ) {
   block.dimension.getEntities({ location: block.location, maxDistance: 15 }).forEach(entity => {
  if (entity.typeId === 'minecraft:player') {
    block.dimension.getPlayers().forEach(player => {
      const mode = player.getGameMode();
player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run function spore_particle`);

      block.setType(Math.random() < 0.95 ? randomgenspore : 'xaierg:mob_tocon');
      if (mode === "creative" || mode === "spectator") return;
      player.runCommand(
        `execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run function spore_c`
      );
      player.runCommand(


        `execute at @e[type=player,tag=!has_mask,r=9] run titleraw @a[r=8] actionbar {"rawtext":[{"text":"§eYou need anti-spore filter!!"}]}`
      );
    });
  }
});
  }
});
}
//antifungico
const TIMER_TAG = "antifungico_active";
const TIMER_SCORE = "mask_timer";
const TIMER_SECONDS = 181; // Cambia a lo que necesites

SERVER.world.afterEvents.itemCompleteUse.subscribe(event => {
  const { itemStack, source } = event;
  if (itemStack.typeId === "xaierg:antifungico" && source.typeId === "minecraft:player") {
    source.removeTag(TIMER_TAG); // Remueve el tag al consumir
    source.setDynamicProperty(TIMER_SCORE, TIMER_SECONDS);
  }
});

SERVER.system.runInterval(() => {
  for (const player of SERVER.world.getPlayers()) {
    let timer = player.getDynamicProperty(TIMER_SCORE);
    if (typeof timer === "number") {
      timer--;
      player.setDynamicProperty(TIMER_SCORE, timer);
      if (timer >= 180) {
         // Muestra el contador solo en el action bar
    
      player.playSound("random.orb", { location: player.location });
        player.sendMessage("§santi-spore protection activated");
      }
      if (timer <= 180 && timer >= 11) {
         // Muestra el contador solo en el action bar
      player.runCommand(`titleraw @s actionbar {"rawtext":[{"text":"§eanti-spore protection: §f${timer}"}]}`);
      }
      if (timer == 11) {
        player.sendMessage("§4You are about to be left without protection");
      }
if (timer <= 11) {
         // Muestra el contador solo en el action bar
      player.runCommand(`titleraw @s actionbar {"rawtext":[{"text":"§eanti-spore protection: §f${timer}"}]}`);

      // Efectos visuales y sonorose
      player.spawnParticle("minecraft:happy_villager", player.location);
      player.playSound("random.orb", { location: player.location })
      }
     

      // Cuando termina el contador, vuelve a añadir el tag
      if (timer <= 0) {
        player.addTag(TIMER_TAG);
        player.setDynamicProperty(TIMER_SCORE, undefined);
        player.sendMessage("§4end of anti-spore protection");
      }
    }
  }
}, 20); // cada segundo
// spores2
SERVER.world.afterEvents.itemCompleteUse.subscribe(event => {
  const { itemStack, source } = event;
  if (itemStack.typeId === "xaierg:antibiotico" && source.typeId === "minecraft:player") {
    source.runCommand(`/effect @s clear wither`);
    
  }
});
registerCustomComponent('xaierg:spores2', {
  onTick: e => spores2(e.block),
  onPlayerDestroy: e => spores2(e.block)
});

function spores2(block) {
  const adjacentBlocks2 = [block.above(1)];
  adjacentBlocks2.forEach(adjacentBlock => {
    if (
      adjacentBlock &&
      [
        'minecraft:air',
        'xaierg:flor1',
        'xaierg:flor2',
        'xaierg:flor3',
        'xaierg:flor4',
        'xaierg:flor5',
        'xaierg:flor6',
        'xaierg:flor7',
        'xaierg:cordyceps_spore',
        'xaierg:cordyceps_layer1',
        'xaierg:cordyceps_layer2',
        'xaierg:cordyceps_layer3',
        'xaierg:cordyceps_layer4',
        'xaierg:cordyceps_layer5'
      ].includes(adjacentBlock.typeId)
    ) {
      block.dimension.getEntities({ location: block.location, maxDistance: 15 }).forEach(entity => {
        if (entity.typeId === 'minecraft:player') {
          block.dimension.getPlayers().forEach(player => {
            const mode = player.getGameMode();
            
player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run function spore_particle`);
            if (mode === "creative" || mode === "spectator") return;
            player.runCommand(
              `execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run function spore_c`
            );
            player.runCommand(
              `execute at @e[type=player,tag=!has_mask,r=9 ] run titleraw @a[r=8] actionbar {"rawtext":[{"text":"§eYou need anti-spore filter!!"}]}`
            );
          });
        }
      });
    }
  });
}

// cordyceps_structureX
registerCustomComponent('xaierg:cordyceps_structureX', {
  onRandomTick: e => structuresCordy(e.block),
  onPlayerDestroy: e => structuresCordy(e.block)
});

function structuresCordy(block) {
  const genstructuresCordy = [
    'cordy1_deco', 'cordy2_deco', 'cordy3_deco', 'cordy4_deco', 'cordy5_deco'
  ];
  const randomgenstructuresCordy = genstructuresCordy[Math.floor(Math.random() * genstructuresCordy.length)];
  const adjacentBlocks2 = [block.above(1)];
  block.setType('xaierg:cordyceps');
  adjacentBlocks2.forEach(adjacentBlock => {
    if (adjacentBlock && ['minecraft:air', 'xaierg:flor1', 'xaierg:flor2', 'xaierg:flor3', 'xaierg:flor4', 'xaierg:flor5', 'xaierg:flor6', 'xaierg:flor7', 'xaierg:cordyceps_layer1', 'xaierg:cordyceps_layer2', 'xaierg:cordyceps_layer3', 'xaierg:cordyceps_layer4', 'xaierg:cordyceps_layer5', 'xaierg:cordyceps_spore'].includes(adjacentBlock.typeId)) {
      block.dimension.getEntities({ location: block.location, maxDistance: 15 }).forEach(entity => {
        if (entity.typeId === 'minecraft:player') {
          block.dimension.getPlayers().forEach(player => {
            player.runCommand(Math.random() < 0.6
        ?`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run structure load ${randomgenstructuresCordy} ~-3~~-3` : `execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run setblock ~~~ xaierg:cordyceps`);
          });
        }
      });
    }
  });
}

// blood_entities (entity hurt particle effect)
SERVER.world.afterEvents.entityHurt.subscribe(data => {
  const creature = data.damageSource.damagingEntity;
  const allowedFamilies = [
    'minecraft:player','xaierg:moto','xaierg:camioneta','xaierg:camioneta_g','xaierg:humbee_fedra'
  ];
  if (!allowedFamilies.includes(creature?.typeId)) return;
  // Si el atacante es una moto, recibe 1 punto de daño
  const vehicleIds = [
    'xaierg:moto',
    'xaierg:camioneta',
    'xaierg:camioneta_g',
    'xaierg:humbee_fedra',
    // Agrega más IDs aquí si lo necesitas
  ];
  if (vehicleIds.includes(creature.typeId)) {
    if (typeof creature.applyDamage === 'function') {
      creature.applyDamage(1);
    }
  }
  const victim = data.hurtEntity;
  if (victim?.typeId === 'minecraft:player') return;
  victim.runCommand('particle xaierg:blooding ^ ^0.5 ^');
  victim.runCommand('particle xaierg:blood_hit ^ ^0.5 ^');
});



// camioneta_bX
registerCustomComponent('xaierg:camioneta_bX', {
  onTick: e => {
    const genstructuresB2 = [
      'structure load camino1 ~ ~-1 ~7', 'structure load camino2 ~ ~-1 ~7', 'structure load camino3 ~ ~-1 ~7',
      'structure load deco_pueblo1 ~ ~ ~7', 'structure load deco_pueblo2 ~ ~ ~7', 'structure load deco_pueblo3 ~ ~ ~7',
      'structure load deco_pueblo4 ~ ~ ~7', 'structure load deco_pueblo5 ~ ~ ~7', 'structure load deco_pueblo6 ~ ~ ~7',
      'structure load deco_pueblo7 ~ ~ ~7', 'structure load deco_pueblo8 ~ ~ ~7', 'structure load deco_pueblo9 ~ ~ ~7',
      'structure load deco_pueblo10 ~ ~ ~7', 'structure load deco_pueblo11 ~ ~ ~7', 'structure load deco_pueblo12 ~ ~ ~7',
      'structure load deco_pueblo13 ~ ~ ~7', 'structure load deco_pueblo14 ~ ~ ~7', 'structure load deco_pueblo15 ~ ~ ~7',
      'structure load deco_pueblo16 ~ ~ ~7', 'structure load deco_pueblo17 ~ ~ ~7', 'structure load deco_pueblo18 ~ ~ ~7',
      'structure load deco_pueblo19 ~ ~ ~7', 'structure load deco_pueblo20 ~ ~ ~7', 'structure load deco_pueblo21 ~ ~ ~7',
      'structure load deco_pueblo22 ~ ~ ~7', 'structure load deco_pueblo23 ~ ~ ~7', 'structure load deco_pueblo24 ~ ~ ~7',
      'structure load deco_pueblo25 ~ ~ ~7', 'structure load deco_pueblo26 ~ ~ ~7', 'structure load deco_pueblo27 ~ ~ ~7',
      'structure load deco_pueblo28 ~ ~ ~7', 'structure load deco_pueblo29 ~ ~ ~7', 'structure load deco_pueblo30 ~ ~ ~7',
      'structure load deco_pueblo31 ~ ~ ~7', 'structure load pueblo_deco5 ~ ~ ~7'
    ];
    const casa = genstructuresB2[Math.floor(Math.random() * genstructuresB2.length)];

    const genstructuresB3 = genstructuresB2.map(s => s.replace('~ ~ ~7', '~7 ~ ~'));
    const casa2 = genstructuresB3[Math.floor(Math.random() * genstructuresB3.length)];

    forEachNearbyPlayer(e.block, 128, (player, block) => {
      player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run ${casa}`);
      player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run ${casa2}`);
      player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run structure load base_casa ~-9 ~-11 ~-9`);
      block.setType('minecraft:moss_block');
    });
  }
});

// pruX
registerCustomComponent('xaierg:pruX', {
  onTick: e => {
    forEachNearbyPlayer(e.block, 5, (player, block) => {
      player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run summon xaierg:camioneta`);
      block.setType('minecraft:air');
    });
  }
});

// spawn_luzX
registerCustomComponent('xaierg:spawn_luzX', {
  onPlayerInteract: e => {
    e.player.runCommand(`execute positioned ${e.block.location.x} ${e.block.location.y} ${e.block.location.z} run function spawn_luz`);
    e.player.runCommand(`particle minecraft:explosion_manual ${e.block.location.x} ${e.block.location.y + 1} ${e.block.location.z}`);
  }
});

// spawn_militaryX
registerCustomComponent('xaierg:spawn_militaryX', {
  onPlayerInteract: e => {
    e.player.runCommand(`execute positioned ${e.block.location.x} ${e.block.location.y} ${e.block.location.z} run function spawn_military`);
    e.player.runCommand(`particle minecraft:explosion_manual ${e.block.location.x} ${e.block.location.y + 1} ${e.block.location.z}`);
  }
});

// spawn_villager1X
registerCustomComponent('xaierg:spawn_villager1X', {
  onTick: e => {
    const genstructuresB2 = ['xaierg:civil', 'xaierg:military', 'villager', 'xaierg:fedra_melee'];
    const picks = Array.from({ length: 5 }, () => genstructuresB2[Math.floor(Math.random() * genstructuresB2.length)]);
    forEachNearbyPlayer(e.block, 128, (player, block) => {
      picks.forEach(summon => {
        player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run summon ${summon} ~~1~`);
      });
      player.runCommand(`particle minecraft:explosion_manual ${block.location.x} ${block.location.y + 1} ${block.location.z}`);
      block.setType('minecraft:stone');
    });
  }
});

// spawn_torreta
registerCustomComponent('xaierg:spawn_torreta', {
  onPlayerInteract: e => {
    e.player.runCommand(`summon xaierg:torreta ${e.block.location.x} ${e.block.location.y + 1} ${e.block.location.z}`);
    e.player.runCommand(`setblock ${e.block.location.x} ${e.block.location.y} ${e.block.location.z} stone`);
  }
});

// spawn_torreta_fire
registerCustomComponent('xaierg:spawn_torreta_fire', {
  onPlayerInteract: e => {
    e.player.runCommand(`summon xaierg:torreta_fire ${e.block.location.x} ${e.block.location.y + 1} ${e.block.location.z}`);
    e.player.runCommand(`setblock ${e.block.location.x} ${e.block.location.y} ${e.block.location.z} stone`);
  }
});

// torreta_bX
registerCustomComponent('xaierg:torreta_bX', {
  onPlayerInteract: e => {
    e.player.runCommand(`execute positioned ${e.block.location.x} ${e.block.location.y} ${e.block.location.z} run structure load torreta ~-1 ~ ~-1`);
    e.player.runCommand(`particle xaierg:explode_granade ${e.block.location.x} ${e.block.location.y + 1} ${e.block.location.z}`);
  }
});

// torreta_fbX
registerCustomComponent('xaierg:torreta_fbX', {
  onPlayerInteract: e => {
    e.player.runCommand(`execute positioned ${e.block.location.x} ${e.block.location.y} ${e.block.location.z} run structure load torreta_fire ~-1 ~ ~-1`);
    e.player.runCommand(`particle minecraft:explosion_manual ${e.block.location.x} ${e.block.location.y + 1} ${e.block.location.z}`);
  }
});



// spawn_cordycepsX
registerCustomComponent('xaierg:spawn_cordycepsX', {
  onTick: e => {
    const genstructuresB2 = [
      'xaierg:dreamer', 'xaierg:stalker', 'xaierg:clicker', 'xaierg:child_clicker',
      'xaierg:dreamer', 'xaierg:stalker', 'xaierg:clicker', 'xaierg:child_clicker',
      'xaierg:dreamer', 'xaierg:stalker', 'xaierg:clicker', 'xaierg:child_clicker',
      'xaierg:clicker', 'xaierg:strongler', 'xaierg:turret_clicker',
      'xaierg:clicker', 'xaierg:clicker', 'xaierg:clicker'
    ];
    const picks = Array.from({ length: 4 }, () => genstructuresB2[Math.floor(Math.random() * genstructuresB2.length)]);
    forEachNearbyPlayer(e.block, 128, (player, block) => {
      picks.forEach(summon => {
        player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run summon ${summon} ~~1~`);
      });
      player.runCommand(`particle minecraft:explosion_manual ${block.location.x} ${block.location.y + 1} ${block.location.z}`);
      block.setType('minecraft:stone');
    });
  }
});

// spawn_hunterX
registerCustomComponent('xaierg:spawn_hunterX', {
  onTick: e => {
    forEachNearbyPlayer(e.block, 128, (_player, block) => {
      block.setType('minecraft:stone');
    });
  }
});

// spawn_scarX
registerCustomComponent('xaierg:spawn_scarX', {
  onTick: e => {
    const genstructuresB2 = ['xaierg:scar_ranged', 'xaierg:scar_melee', 'xaierg:scar_ranged', 'xaierg:scar_ranged', 'xaierg:scar_melee', 'xaierg:scar_melee'];
    const picks = Array.from({ length: 4 }, () => genstructuresB2[Math.floor(Math.random() * genstructuresB2.length)]);
    forEachNearbyPlayer(e.block, 128, (player, block) => {
      picks.forEach(summon => {
        player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run summon ${summon} ~~1~`);
      });
      player.runCommand(`particle minecraft:explosion_manual ${block.location.x} ${block.location.y + 1} ${block.location.z}`);
      block.setType('minecraft:stone');
    });
  }
});

// spawn_wolfX
registerCustomComponent('xaierg:spawn_wolfX', {
  onTick: e => {
    const genstructuresB2 = ['xaierg:wolf_melee', 'xaierg:wolf_ranged', 'xaierg:wolf_melee', 'xaierg:wolf_melee', 'xaierg:wolf_melee', 'xaierg:wolf_ranged'];
    const picks = Array.from({ length: 4 }, () => genstructuresB2[Math.floor(Math.random() * genstructuresB2.length)]);
    forEachNearbyPlayer(e.block, 128, (player, block) => {
      picks.forEach(summon => {
        player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run summon ${summon} ~~1~`);
      });
      player.runCommand(`particle minecraft:explosion_manual ${block.location.x} ${block.location.y + 1} ${block.location.z}`);
      block.setType('minecraft:stone');
    });
  }
});

// event_hunterX, event_hunter2X, event_hunter3X, event_hunter4X
['event_hunterX', 'event_hunter2X', 'event_hunter3X', 'event_hunter4X'].forEach(eventID => {
  registerCustomComponent(`xaierg:${eventID}`, {
    onTick: e => {
      forEachNearbyPlayer(e.block, 128, (player, block) => {
        player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run function ${eventID.replace('X', null)}`);
      });
    }
  });
});

