import { world, system, EntityComponentTypes } from '@minecraft/server';

const REQUIRED_KILL_ITEM_ID = "mebesm:kill_sign";
const DEATH_TAG = "DeathMe";

// 1. РЕГИСТРАЦИЯ КОМПОНЕНТОВ БЛОКОВ
world.beforeEvents.worldInitialize.subscribe(initEvent => {
  const registry = initEvent.blockComponentRegistry;

  // Компонент для mebesm_mebesm
  registry.registerCustomComponent('myaddon:interactive_block_trigger', {
    onPlayerInteract: e => {
      e.player.runCommandAsync("playsound block.mebesm_mebesm @p");
    },
  });

  // НОВЫЙ КОМПОНЕНТ ДЛЯ LIMON_TOY
  registry.registerCustomComponent('mebesm:limon_toy_trigger', {
    onPlayerInteract: e => {
      e.player.runCommandAsync("playsound limon @p");
    },
  });
});

// 2. ЛОГИКА УДАРА (ПРИСВОЕНИЕ ТЕГА)
world.afterEvents.entityHitEntity.subscribe(event => {
  const { damagingEntity, hitEntity } = event;

  if (damagingEntity?.typeId !== "minecraft:player" || hitEntity.typeId === "minecraft:player") return;

  const equipment = damagingEntity.getComponent(EntityComponentTypes.Equippable);
  const mainhandItem = equipment?.getEquipment("Mainhand");

  if (mainhandItem?.typeId === REQUIRED_KILL_ITEM_ID && !hitEntity.hasTag(DEATH_TAG)) {
    hitEntity.addTag(DEATH_TAG);
    damagingEntity.runCommand(`execute at @s run playsound random.break @a ~ ~ ~ 0.5 0.8`);
  }
});

// 3. ЛОГИКА СМЕРТИ
system.runInterval(() => {
  const dimensions = ["overworld", "nether", "the_end"];

  for (const dimId of dimensions) {
    try {
      const dimension = world.getDimension(dimId);
      const taggedEntities = dimension.getEntities({
        tags: [DEATH_TAG],
        excludeTypes: ["minecraft:player"]
      });

      for (const entity of taggedEntities) {
        if (entity.isValid()) {
          entity.kill();
        }
      }
    } catch (e) { }
  }
}, 5);