// Import necessary modules from Minecraft server API
import { world, ItemStack, BlockPermutation } from "@minecraft/server";

export const fakeBoneBlockComponent = {
  onTick({ block }) {
    const timeOfDay = world.getTimeOfDay(); // 0 - 23999
    const isNight = timeOfDay >= 12500 && timeOfDay <= 23500;
    if (!isNight) return;
    let nearbyLostSouls = block.dimension.getEntities({
      location: block.location,
      type: "hb_hr:agressive_lost_soul",
      maxDistance: 40,
    });
    if (nearbyLostSouls.length >= 3) return;

    let loc;
    const neighbours = [
      { x: block.location.x + 1, y: block.location.y, z: block.location.z },
      { x: block.location.x - 1, y: block.location.y, z: block.location.z },
      { x: block.location.x, y: block.location.y, z: block.location.z + 1 },
      { x: block.location.x, y: block.location.y, z: block.location.z - 1 },

      { x: block.location.x + 1, y: block.location.y + 1, z: block.location.z },
      { x: block.location.x - 1, y: block.location.y + 1, z: block.location.z },
      { x: block.location.x, y: block.location.y + 1, z: block.location.z + 1 },
      { x: block.location.x, y: block.location.y + 1, z: block.location.z - 1 },

      { x: block.location.x + 1, y: block.location.y + 2, z: block.location.z },
      { x: block.location.x - 1, y: block.location.y + 2, z: block.location.z },
      { x: block.location.x, y: block.location.y + 2, z: block.location.z + 1 },
      { x: block.location.x, y: block.location.y + 2, z: block.location.z - 1 },
    ];
    for (const pos of neighbours) {
      const neighborBlock = block.dimension.getBlock(pos);
      // Only spread if the neighbour is a valid target.
      if (neighborBlock && neighborBlock.typeId == "minecraft:air") {
        loc = neighborBlock.center();
        break;
      }
    }
    try {
      block.dimension.spawnParticle("hb_hr:lost_soul_state_change", loc);
    } catch (error) {}
    block.dimension.spawnEntity("hb_hr:agressive_lost_soul<hb_hr:can_be_hurt>", loc);
    return;
  },
};

const customComponents = {
  "hb_hr:fake_bone_block": fakeBoneBlockComponent,
};

export function fakeBoneBlock() {
  world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
    for (const [componentName, componentImplementation] of Object.entries(customComponents)) {
      blockComponentRegistry.registerCustomComponent(componentName, componentImplementation);
    }
  });
}
