
//world.afterEvents.projectileHitEntity.subscribe((arg) => {
//  const hitEntity = arg.getEntityHit()?.entity;
//  const { projectile, source } = arg;
//
//  if (
//    !hitEntity ||
//    hitEntity.typeId !== "minecraft:player" ||
//    !source ||
//    source.typeId !== "minecraft:player" ||
//    !projectile ||
//    !["minecraft:fishing_hook"].includes(projectile.typeId) ||
//    hitEntity.id === source.id
//  ) {
//    return;
//  }
//
//  hitEntity.applyDamage(0.5);
//
//  const direction = source.getViewDirection();
//  hitEntity.applyKnockback(direction.x, direction.z, 1.5, 0.5);
//
//  system.runTimeout(() => {
//    source.spawnParticle("minecraft:basic_flame_particle", projectile.location);


world.afterEvents.entityDie.subscribe(({ deadEntity, damageSource: { damagingEntity } }) => {
  if (damagingEntity?.typeId !== 'minecraft:player') return;

  const family = deadEntity.getComponent('type_family');
  if (!family) return;

  // Mapeamento: família => lista de comandos
  const commandsByFamily = {
    boss1: [
        'scoreboard players set @s [tag=boss1, r=50] Selva 1',
        'tp @s ~~1~',
        'execute as @s [tag=boss1, r=50] run tellraw @a {\"rawtext\":[{\"selector\": \"@s[r=15, tag=boss1, c=1]\"}, { \"translate\":\"missao.concluida.boss1.morto\" }]}',
        'tag @s [tag=boss1, r=50] add adventure',
        'tag @s [tag=boss1, r=50] remove boss1',
        'titleraw @s [tag=adventure, r=20] title {\"rawtext\":[{ \"translate\":\"missao.atualizacao.titulo\" }]}',
        'titleraw @s [tag=adventure, r=20] subtitle {\"rawtext\":[{ \"translate\":\"missao.atualizacao.subtitulo\" }]}',
        'playsound missioncomplete @s [tag=adventure, r=20] ~ ~ ~',
        'stopsound @s dungeon_music',
        'stopsound @s Boss1',
        'music stop 1',
		'scoreboard players set @s [tag=adventure, r=50] missaowell5 1'
	],
	boss2: [
        'tp @s ~~1~',
		'tag @s [tag=boss2, r=50] add master',
		'tag @s [tag=boss2, r=50] remove boss2',
		'execute as @s [tag=master, r=50] run tellraw @a {\"rawtext\":[{\"selector\": \"@s[r=15, tag=master, c=1]\"}, { \"translate\":\"missao.concluida.boss2.morto\" }]}',
		'stopsound @s dungeon_music',
		'stopsound @s Boss2',
		'music stop 1',
		'titleraw @s [tag=master, r=20] title {\"rawtext\":[{ \"translate\":\"missao.atualizacao.titulo\" }]}',
		'titleraw @s [tag=master, r=20] subtitle {\"rawtext\":[{ \"translate\":\"missao.atualizacao.subtitulo\" }]}',
		'playsound missioncomplete @s [tag=master, r=20] ~ ~ ~',
		'scoreboard players set @s [tag=master, r=50] missaowell10 1'
	],
	
	boss3: [
        'tp @s ~~1~',
		'execute as @s [tag=boss3, r=50] run tellraw @a {\"rawtext\":[{\"selector\": \"@a[r=15, tag=boss3, c=1]\"}, { \"translate\":\"missao.concluida.boss3.morto\" }]}',
		'tag @s [tag=boss3, r=50] add hero',
		'tag @s [tag=boss3, r=50] remove boss3',
		'titleraw @s [tag=hero, r=20] title {\"rawtext\":[{ \"translate\":\"missao.atualizacao.titulo\" }]}',
		'titleraw @s [tag=hero, r=20] subtitle {\"rawtext\":[{ \"translate\":\"missao.atualizacao.subtitulo\" }]}',
		'playsound missioncomplete @s [tag=hero, r=20] ~ ~ ~',
		'stopsound @s dungeon_music',
		'stopsound @s Boss1',
		'scoreboard players set @s [tag=hero, r=50] missaowell13 1',
		'music stop 1'
	],
	
	
	
	zombie: [
        'scoreboard players add @s zumbi 1',
		'titleraw @s [scores={zumbi=..20}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.zumbi\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.zumbi.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"zumbi\"}}, {\"translate\": \"barra.vinte\"}]}',
		'titleraw @s [scores={zumbi=..20}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.zumbi\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.zumbi.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"zumbi\"}}, {\"translate\": \"barra.vinte\"}]}',
		'titleraw @s [scores={zumbi=..20}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.zumbi\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.zumbi.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"zumbi\"}}, {\"translate\": \"barra.vinte\"}]}',
		'titleraw @s [scores={zumbi=..20}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.zumbi\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.zumbi.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"zumbi\"}}, {\"translate\": \"barra.vinte\"}]}',
		'titleraw @s [scores={zumbi=..20}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.zumbi\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.zumbi.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"zumbi\"}}, {\"translate\": \"barra.vinte\"}]}',
		'titleraw @s [scores={zumbi=..20}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.zumbi\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.zumbi.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"zumbi\"}}, {\"translate\": \"barra.vinte\"}]}',
		'titleraw @s [scores={zumbi=..20}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.zumbi\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.zumbi.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"zumbi\"}}, {\"translate\": \"barra.vinte\"}]}',
		'titleraw @s [scores={zumbi=..20}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.zumbi\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.zumbi.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"zumbi\"}}, {\"translate\": \"barra.vinte\"}]}',
		'titleraw @s [scores={zumbi=..20}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.zumbi\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.zumbi.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"zumbi\"}}, {\"translate\": \"barra.vinte\"}]}',
		'titleraw @s [scores={zumbi=..20}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.zumbi\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.zumbi.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"zumbi\"}}, {\"translate\": \"barra.vinte\"}]}'
    ],
    skeleton: [
        'scoreboard players add @s esqueleto 1',
		'scoreboard players add @s [r=10, tag=adventure, scores={horda=0..}] horda 1',
		'scoreboard players add @s [r=10, tag=adventure, scores={horda=0..}] horda_iniciada 1',
		'titleraw @s [scores={esqueleto=..30}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.esqueleto\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.skeleton.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\", \"objective\": \"esqueleto\"}}, {\"translate\": \"barra.trinta\"}]}',
		'titleraw @s [scores={esqueleto=..30}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.esqueleto\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.skeleton.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\", \"objective\": \"esqueleto\"}}, {\"translate\": \"barra.trinta\"}]}',
		'titleraw @s [scores={esqueleto=..30}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.esqueleto\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.skeleton.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\", \"objective\": \"esqueleto\"}}, {\"translate\": \"barra.trinta\"}]}',
		'titleraw @s [scores={esqueleto=..30}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.esqueleto\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.skeleton.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\", \"objective\": \"esqueleto\"}}, {\"translate\": \"barra.trinta\"}]}',
		'titleraw @s [scores={esqueleto=..30}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.esqueleto\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.skeleton.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\", \"objective\": \"esqueleto\"}}, {\"translate\": \"barra.trinta\"}]}',
		'titleraw @s [scores={esqueleto=..30}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.esqueleto\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.skeleton.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\", \"objective\": \"esqueleto\"}}, {\"translate\": \"barra.trinta\"}]}',
		'titleraw @s [scores={esqueleto=..30}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.esqueleto\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.skeleton.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\", \"objective\": \"esqueleto\"}}, {\"translate\": \"barra.trinta\"}]}',
		'titleraw @s [scores={esqueleto=..30}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.esqueleto\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.skeleton.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\", \"objective\": \"esqueleto\"}}, {\"translate\": \"barra.trinta\"}]}',
		'titleraw @s [scores={esqueleto=..30}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.esqueleto\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.skeleton.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\", \"objective\": \"esqueleto\"}}, {\"translate\": \"barra.trinta\"}]}',
		'titleraw @s [scores={esqueleto=..30}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.esqueleto\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.skeleton.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\", \"objective\": \"esqueleto\"}}, {\"translate\": \"barra.trinta\"}]}',
		'titleraw @s [scores={esqueleto=31..50}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.esqueleto.divino\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.skeleton.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\", \"objective\": \"esqueleto\"}}, {\"translate\": \"barra.cinquenta\"}]}',
		'titleraw @s [scores={esqueleto=31..50}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.esqueleto.divino\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.skeleton.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\", \"objective\": \"esqueleto\"}}, {\"translate\": \"barra.cinquenta\"}]}',
		'titleraw @s [scores={esqueleto=31..50}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.esqueleto.divino\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.skeleton.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\", \"objective\": \"esqueleto\"}}, {\"translate\": \"barra.cinquenta\"}]}',
		'titleraw @s [scores={esqueleto=31..50}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.esqueleto.divino\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.skeleton.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\", \"objective\": \"esqueleto\"}}, {\"translate\": \"barra.cinquenta\"}]}',
		'titleraw @s [scores={esqueleto=31..50}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.esqueleto.divino\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.skeleton.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\", \"objective\": \"esqueleto\"}}, {\"translate\": \"barra.cinquenta\"}]}',
		'titleraw @s [scores={esqueleto=31..50}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.esqueleto.divino\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.skeleton.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\", \"objective\": \"esqueleto\"}}, {\"translate\": \"barra.cinquenta\"}]}',
		'titleraw @s [scores={esqueleto=31..50}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.esqueleto.divino\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.skeleton.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\", \"objective\": \"esqueleto\"}}, {\"translate\": \"barra.cinquenta\"}]}',
		'titleraw @s [scores={esqueleto=31..50}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.esqueleto.divino\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.skeleton.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\", \"objective\": \"esqueleto\"}}, {\"translate\": \"barra.cinquenta\"}]}',
		'titleraw @s [scores={esqueleto=31..50}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.esqueleto.divino\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.skeleton.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\", \"objective\": \"esqueleto\"}}, {\"translate\": \"barra.cinquenta\"}]}',
		'titleraw @s [scores={esqueleto=31..50}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.esqueleto.divino\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.skeleton.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\", \"objective\": \"esqueleto\"}}, {\"translate\": \"barra.cinquenta\"}]}'
    ],
    arthropod: [
        'scoreboard players add @s aranha 1',
		'titleraw @s [scores={aranha=..10}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.aranha\" }, {\"text\": \" \n\"}, { \"translate\":\"entity.aranha.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"aranha\"}}, {\"translate\": \"barra.dez\"}]}',
		'titleraw @s [scores={aranha=..10}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.aranha\" }, {\"text\": \" \n\"}, { \"translate\":\"entity.aranha.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"aranha\"}}, {\"translate\": \"barra.dez\"}]}',
		'titleraw @s [scores={aranha=..10}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.aranha\" }, {\"text\": \" \n\"}, { \"translate\":\"entity.aranha.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"aranha\"}}, {\"translate\": \"barra.dez\"}]}',
		'titleraw @s [scores={aranha=..10}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.aranha\" }, {\"text\": \" \n\"}, { \"translate\":\"entity.aranha.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"aranha\"}}, {\"translate\": \"barra.dez\"}]}',
		'titleraw @s [scores={aranha=..10}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.aranha\" }, {\"text\": \" \n\"}, { \"translate\":\"entity.aranha.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"aranha\"}}, {\"translate\": \"barra.dez\"}]}',
		'titleraw @s [scores={aranha=..10}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.aranha\" }, {\"text\": \" \n\"}, { \"translate\":\"entity.aranha.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"aranha\"}}, {\"translate\": \"barra.dez\"}]}',
		'titleraw @s [scores={aranha=..10}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.aranha\" }, {\"text\": \" \n\"}, { \"translate\":\"entity.aranha.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"aranha\"}}, {\"translate\": \"barra.dez\"}]}',
		'titleraw @s [scores={aranha=..10}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.aranha\" }, {\"text\": \" \n\"}, { \"translate\":\"entity.aranha.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"aranha\"}}, {\"translate\": \"barra.dez\"}]}',
		'titleraw @s [scores={aranha=..10}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.aranha\" }, {\"text\": \" \n\"}, { \"translate\":\"entity.aranha.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"aranha\"}}, {\"translate\": \"barra.dez\"}]}',
		'titleraw @s [scores={aranha=..10}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.aranha\" }, {\"text\": \" \n\"}, { \"translate\":\"entity.aranha.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"aranha\"}}, {\"translate\": \"barra.dez\"}]}'
    ],
    witch: [
        'scoreboard players add @s bruxa 1',
		'titleraw @s [scores={bruxa=..10}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.bruxa\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.bruxa.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"bruxa\"}}, {\"translate\": \"barra.dez\"}]}',
		'titleraw @s [scores={bruxa=..10}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.bruxa\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.bruxa.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"bruxa\"}}, {\"translate\": \"barra.dez\"}]}',
		'titleraw @s [scores={bruxa=..10}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.bruxa\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.bruxa.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"bruxa\"}}, {\"translate\": \"barra.dez\"}]}',
		'titleraw @s [scores={bruxa=..10}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.bruxa\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.bruxa.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"bruxa\"}}, {\"translate\": \"barra.dez\"}]}',
		'titleraw @s [scores={bruxa=..10}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.bruxa\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.bruxa.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"bruxa\"}}, {\"translate\": \"barra.dez\"}]}',
		'titleraw @s [scores={bruxa=..10}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.bruxa\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.bruxa.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"bruxa\"}}, {\"translate\": \"barra.dez\"}]}',
		'titleraw @s [scores={bruxa=..10}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.bruxa\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.bruxa.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"bruxa\"}}, {\"translate\": \"barra.dez\"}]}',
		'titleraw @s [scores={bruxa=..10}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.bruxa\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.bruxa.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"bruxa\"}}, {\"translate\": \"barra.dez\"}]}',
		'titleraw @s [scores={bruxa=..10}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.bruxa\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.bruxa.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"bruxa\"}}, {\"translate\": \"barra.dez\"}]}',
		'titleraw @s [scores={bruxa=..10}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.bruxa\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.bruxa.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"bruxa\"}}, {\"translate\": \"barra.dez\"}]}'
    ],
    enderman: [
        'scoreboard players add @s enderman 1',
		'titleraw @s [scores={enderman=..30}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.enderman\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.enderman.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"enderman\"}}, {\"translate\": \"barra.trinta\"}]}',
		'titleraw @s [scores={enderman=..30}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.enderman\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.enderman.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"enderman\"}}, {\"translate\": \"barra.trinta\"}]}',
		'titleraw @s [scores={enderman=..30}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.enderman\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.enderman.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"enderman\"}}, {\"translate\": \"barra.trinta\"}]}',
		'titleraw @s [scores={enderman=..30}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.enderman\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.enderman.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"enderman\"}}, {\"translate\": \"barra.trinta\"}]}',
		'titleraw @s [scores={enderman=..30}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.enderman\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.enderman.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"enderman\"}}, {\"translate\": \"barra.trinta\"}]}',
		'titleraw @s [scores={enderman=..30}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.enderman\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.enderman.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"enderman\"}}, {\"translate\": \"barra.trinta\"}]}',
		'titleraw @s [scores={enderman=..30}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.enderman\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.enderman.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"enderman\"}}, {\"translate\": \"barra.trinta\"}]}',
		'titleraw @s [scores={enderman=..30}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.enderman\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.enderman.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"enderman\"}}, {\"translate\": \"barra.trinta\"}]}',
		'titleraw @s [scores={enderman=..30}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.enderman\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.enderman.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"enderman\"}}, {\"translate\": \"barra.trinta\"}]}',
		'titleraw @s [scores={enderman=..30}] actionbar { \"rawtext\": [ { \"translate\":\"up.armadura.level.enderman\" }, {\"text\": \"\n\"}, { \"translate\":\"entity.enderman.death\" }, {\"text\": \" \"}, {\"score\":{\"name\": \"@s\",\"objective\": \"enderman\"}}, {\"translate\": \"barra.trinta\"}]}'
    ],
	fantasma_labirinto: [
        'scoreboard players set @s [tag=boss3] fantasma_morto 1'
    ]
	//creeper: [
    //  'say BOOM! Você matou um creeper!',
    //  'effect @s minecraft:resistance 5 1 true'
    //],
    //warden: [
    //  'say VOCÊ MATOU O WARDEN! INSANO!',
    //  'title @s actionbar Você é corajoso!',
    //  'effect @s minecraft:strength 10 2 true'
    //],
    //illager: [
    //  'say Um illager a menos!',
    //  'give @s minecraft:emerald 1'
    //]
  };

  for (const [familyName, commands] of Object.entries(commandsByFamily)) {
    if (family.hasTypeFamily(familyName)) {
      // Executa todos os comandos associados àquela família
      for (const cmd of commands) {
        damagingEntity.runCommand(cmd);
      }
      break; // Para após encontrar a primeira família compatível
    }
  }
});




/**
 * @param {Player} player The player to save the inventory of
 * @param {string} [invName] Identifier of the dynamic property
 * @param {Player} storage The player to set the dynamic property on
 * @returns {{items: string[], wornArmor: string[]}}
 */
function saveInventory(player, invName = player.name, storage = player) {
    let { container, inventorySize } = player.getComponent("inventory");
    const items = [];
    const listOfEquipmentSlots = ["Head", "Chest", "Legs", "Feet", "Offhand"];
    let wornArmor = [];
    for (let i = 0; i < listOfEquipmentSlots.length; i++) {
        const equipment = player.getComponent("equippable").getEquipment(listOfEquipmentSlots[i]);
        if (!equipment) {
            wornArmor.push(null);
            continue;
        }
        const data = {
            typeId: equipment.typeId,
            props: {
                amount: equipment.amount,
                keepOnDeath: equipment.keepOnDeath,
                lockMode: equipment.lockMode
            },
            lore: equipment.getLore(),
            components: {}
        };
        if (equipment.nameTag) data.props.nameTag = equipment.nameTag;
        if (equipment.hasComponent("enchantable")) {
            data.components.enchantable = equipment.getComponent("enchantable").getEnchantments().map(e => ({ type: e.type.id, level: e.level }));
        }
        if (equipment.hasComponent("durability")) {
            data.components.durability = equipment.getComponent("durability").damage;
        }
        wornArmor.push(data);
    }
    storage.setDynamicProperty(`armor:${invName}`, JSON.stringify(wornArmor));

    for (let i = 0; i < inventorySize; i++) {
        const item = container.getItem(i);
        if (!item) {
            items.push(null);
            continue;
        }
        const data = {
            typeId: item.typeId,
            props: {
                amount: item.amount,
                keepOnDeath: item.keepOnDeath,
                lockMode: item.lockMode
            },
            lore: item.getLore(),
            components: {}
        };
        if (item.nameTag) data.props.nameTag = item.nameTag;
        if (item.hasComponent("enchantable")) {
            data.components.enchantable = item.getComponent("enchantable").getEnchantments().map(e => ({ type: e.type.id, level: e.level }));
        }
        if (item.hasComponent("durability")) {
            data.components.durability = item.getComponent("durability").damage;
        }
        items.push(data);
    }
    storage.setDynamicProperty(`inventory:${invName}`, JSON.stringify(items));
    return {items, wornArmor};
}

/**
 * @param {Player} player The player to load the inventory to.
 * @param {string} [invName=player.name] Identifier of the dynamic property to load the items from
 * @param {Player} storage The player to get the dynamic property from
 * @returns {void}
 */
function loadInventory(player, invName = player.name, storage = player) {
    let { container, inventorySize } = player.getComponent("inventory");
    const items = JSON.parse(storage.getDynamicProperty(`inventory:${invName}`) ?? "[]");
    const wornArmor = JSON.parse(storage.getDynamicProperty(`armor:${invName}`) ?? "[]");
    const listOfEquipmentSlots = ["Head", "Chest", "Legs", "Feet", "Offhand"];
    const equipment = player.getComponent("equippable");

    for (let i = 0; i < listOfEquipmentSlots.length; i++) {
        const data = wornArmor[i];
        if (!data) {
            equipment.setEquipment(listOfEquipmentSlots[i], null);
        } else {
            const item = new ItemStack(data.typeId);
            for (const key in data.props) {
                item[key] = data.props[key];
            }
            item.setLore(data.lore);
            if (data.components?.enchantable) {
                item.getComponent("enchantable").addEnchantments(
                    data.components.enchantable.map(e => ({ ...e, type: new EnchantmentType(e.type) }))
                );
            }
            if (data.components?.durability) {
                item.getComponent("durability").damage = data.components.durability;
            }
            equipment.setEquipment(listOfEquipmentSlots[i], item);
        }
    }

    for (let i = 0; i < inventorySize; i++) {
        const data = items[i];
        if (!data) {
            container.setItem(i, null);
        } else {
            const item = new ItemStack(data.typeId);
            for (const key in data.props) {
                item[key] = data.props[key];
            }
            item.setLore(data.lore);
            if (data.components?.enchantable) {
                item.getComponent("enchantable").addEnchantments(
                    data.components.enchantable.map(e => ({ ...e, type: new EnchantmentType(e.type) }))
                );
            }
            if (data.components?.durability) {
                item.getComponent("durability").damage = data.components.durability;
            }
            container.setItem(i, item);
        }
    }
}


world.afterEvents.itemUse.subscribe((data) => {
    const { itemStack: item, source: player } = data;

    if (item.typeId == "minecraft:diamond_sword") {
        saveInventory(player);

        // Imediatamente equipa o item "well:susto" na cabeça
        const equipment = player.getComponent("equippable");
        const sustoItem = new ItemStack("well:susto");
        equipment.setEquipment("Head", sustoItem);

        const inv = player.getComponent("inventory").container;
        for (let i = 0; i < inv.size; i++) {
            inv.setItem(i, new ItemStack("minecraft:barrier"));
        }

        player.runCommand("say Capacete de susto colocado! Inventário será restaurado em 5 segundos.");

        system.runTimeout(() => {
            loadInventory(player);
            player.runCommand("say Inventário e armadura restaurados!");
        }, 20 * 5);
    }
});









//import { biomeList, biomeOptions } from "./biomes";
//import { blocksDistanceMath } from "./blocksDistance";

//Impedir colocar Bloco de Bedrock e enviar mensagem no chat
//world.beforeEvents.itemUseOn.subscribe(event => {
//    if (event.itemStack.typeId === "minecraft:bedrock" && event.block.typeId != "minecraft:frame" && event.block.typeId != "minecraft:glow_frame") {
//        event.cancel = true;
//        system.run(() => {
//            const player = event.source
//            player.sendMessage(`You cannot place Bedrock`)
//        });
//    }
//});



//const whoJumped = {}; // Add this line to declare the 'whoJumped' object
//
//const strength = 0.3;
//const vertical = 0.3;
//
//system.runInterval(() => {
//    const players = world.getPlayers({ excludeGameModes: ["creative"] });
//    for (let i = 0; i < players.length; i++) {
//        const player = players[i];
//        if (player.isOnGround) {
//            player.hasJumped = false;
//            continue;
//        }
//        if (player.hasJumped) continue;
//        system.runTimeout(() => {
//            if (player.isJumping) {
//                player.hasJumped = true;
//                const di = player.getViewDirection();
//                player.applyKnockback(di.x, di.z, strength, di.y + vertical);
//				player.runCommand(`playanimation @s animation.humanoid.esquiva.frente`)
//            }
//        }, 3);
//    }
//}, 3);

//world.afterEvents.playerJoin.subscribe((data) => {
//    whoJumped[data.playerName] = false;
//});
//
//world.afterEvents.playerLeave.subscribe((data) => {
//    delete whoJumped[data.playerName];
//});


//function getTime() {
//    const tempo = new Date()
//    const data = tempo.getDay()
//    const dia = tempo.getDate()
//    const mes= tempo.getMonth() + 1
//    const ano = tempo.getFullYear()
//    const hora = (tempo.getUTCHours() + 24 - 4) % 24
//    const min= tempo.getMinutes()
//    const seg = tempo.getSeconds()
//    let diaSemana = null
//
//    switch (data) {
//        case 0:
//            diaSemana = "Domingo"
//            break;
//        case 1:
//            diaSemana = "Segunda-feira"
//            break;
//        case 2:
//            diaSemana = "Terça-feira"
//            break;
//        case 3:
//            diaSemana = "Quarta-feira"
//            break;
//        case 4:
//            diaSemana = "Quinta-feira"
//            break;
//        case 5:
//            diaSemana = "Sexta-feira"
//            break;
//        case 6:
//            diaSemana = "Sábado"
//            break;
//    }
//
//    return `Brasília: ${diaSemana} ${dia}/${mes}/${ano} - ${hora}:${min}:${seg}`
//}
//
//system.runInterval(() => {
//    for (const player of world.getAllPlayers()) {
//        player.onScreenDisplay.setActionBar(`${getTime()}`)
//    }
//})



function checkWaterDepth(player) {
    let positionY = Math.floor(player.location.y);

    if (positionY <= 10 && player.dimension.id === 'minecraft:overworld') {
        let blockLocation = {
            x: Math.floor(player.location.x),
            y: positionY,
            z: Math.floor(player.location.z)
        };
        let block = player.dimension.getBlock(blockLocation);

        if (block && block.typeId === 'minecraft:water') {
            //player.runCommand('title @s actionbar Você está na água na profundidade Y = 10!');
            //player.runCommand('fog @s push "well:sombras" "well:sombras"');
			player.runCommand('effect @s [hasitem={item=well:capacete_de_prismarinho, location=slot.armor.head, quantity=0}] blindness 90000000 20 true');
			player.runCommand('effect @s [hasitem={item=well:capacete_de_prismarinho, location=slot.armor.head, quantity=1}] blindness 0 0 true');
        }
    } else if (positionY > 10 && player.dimension.id === 'minecraft:overworld') {
        //player.runCommand('title @s actionbar Você está acima da profundidade Y = 10!');
        //player.runCommand('fog @s remove "well:sombras"');
		player.runCommand('effect @s blindness 0 0 true');
    }
}

function monitorPlayersInWater() {
    const players = world.getPlayers();

    for (let player of players) {
        let blockLocation = {
            x: Math.floor(player.location.x),
            y: Math.floor(player.location.y),
            z: Math.floor(player.location.z)
        };
        let block = player.dimension.getBlock(blockLocation);

        if (block && block.typeId === 'minecraft:water') {
            const intervalId = system.runInterval(() => checkWaterDepth(player), 30); // Reduzido para 1 verificação a cada 10 ticks

            const exitCheck = system.runInterval(() => {
                let currentBlock = player.dimension.getBlock(blockLocation);

                if (!currentBlock || currentBlock.typeId !== 'minecraft:water') {
                    system.clearRun(intervalId);
                    system.clearRun(exitCheck);
                }
            }, 30); // Reduzido para verificar saída a cada 10 ticks
        }
    }
}

// Inicia o monitoramento dos jogadores entrando na água a cada 10 ticks
system.runInterval(monitorPlayersInWater, 30);

//world.afterEvents.itemUse.subscribe((eventData) => {
//    if (eventData.itemStack.typeId === "well:alma") {
//        let player = eventData.source;
//        openForm9(player);
//    }
//});
//
//
//function openForm9(player, callback) {
//  const players = world.getAllPlayers().map(p => p.name);
//  const form = new ModalFormData()
//    .title('Selecionar jogador')
//    .dropdown('Jogadores online:', players);
//
//  form.show(player).then(({ formValues, canceled, cancelationReason }) => {
//    if (cancelationReason === 'UserBusy') return openForm9(player, callback);
//    if (canceled || formValues === undefined) return;
//
//    const selectedName = players[formValues[0]];
//    const selectedPlayer = world.getPlayers({ name: selectedName })[0];
//
//    if (selectedPlayer && typeof callback === 'function') {
//      callback(selectedPlayer);
//    } else {
//      player.sendMessage('Jogador não encontrado.');
//    }
//  });
//}
//


//world.afterEvents.playerInteractWithEntity.subscribe(({player, target}) => {
//    if (target.typeId === "minecraft:wandering_trader") {
//        {locateBiomeMenu(player)}
//    }
//})

//Comandos personalizados no chat
world.beforeEvents.chatSend.subscribe((eventData) => {
	const player = eventData.sender;
	switch (eventData.message) {
		case '!gmc':
			eventData.cancel = true;
			player.runCommand('gamemode c');
			break;
		case '!start_mod':
			eventData.cancel = true;
			player.runCommand('tag @s remove congelado');
			player.runCommand('title @s title §´CODIGO EXECUTADO');
			player.runCommand('title @s subtitle §´COM SUCESSO!!');
			
			player.runCommand('replaceitem entity @s slot.hotbar 0 well:cajado_mago 1 0 {"item_lock": {"mode": "lock_in_slot"}, "keep_on_death": {}}');
            player.runCommand('tag @s remove genero');
            player.runCommand('tag @s add novice');
            
            player.runCommand('scoreboard players set @s genero 1');
            
            player.runCommand('event entity @a remover_estado_invuneravel');
            
            player.runCommand('scoreboard players set @s classe_mago 1');
            player.runCommand('scoreboard players set @s skill_mago 0');
            player.runCommand('scoreboard players set @s skill_mago_orbe 0');
            player.runCommand('scoreboard players set @s classe_elfo 0');
            player.runCommand('scoreboard players set @s classe_humana 0');
            player.runCommand('tag @s add subquest0');
            player.runCommand('tag @s remove congelado_cinematica');
								   
            player.runCommand('effect @s water_breathing 0 0 true');
            player.runCommand('effect @s invisibility 0 0 true');
            player.runCommand('tp @s 35 70 7');
								   
            player.runCommand('inputpermission set @s movement enabled');
            player.runCommand('inputpermission set @s camera enabled');
            player.runCommand('camera @s clear');
			break;
		default: break;
	}
});


//Itens na mão serão renomeados ao segurar
//system.runInterval(() => {
//  // Loop over all the players
//  for (const player of world.getPlayers()) {
//    // Get the player container
//    const container = player.getComponent('inventory')?.container;
//    // Get the item in the selected slot
//    const item = container.getItem(player.selectedSlot);
//    if (!item) continue;
//    
//    // Handle all the possible item identifiers
//    switch (item.typeId) {
//		case "well:mesa_transmutacao":
//        item.setLore([  '',  'Wells RPG Adventure']);
//        break;
//		case "well:mesa_purificacao":
//        item.setLore([  '',  'Wells RPG Adventure']);
//        break;
//		
//      default:
//        continue;
//        break;
//    }
//
//    // Set the modified item back to the selected slot
//    container.setItem(player.selectedSlot, item);
//  }
//});
//

function admin_menu(player) {

    	var playerObjects = []
        var listaJogadores = []

        var players = world.getPlayers()
        
        for (let jogadores of players) {
            listaJogadores.push(jogadores.name)
            playerObjects.push(jogadores)
        }
  const modal = new ModalFormData()
    .title({ "rawtext": [{ "translate": "admin.titulo" }]})
    .dropdown({ "rawtext": [{ "translate": "admin.dropdown" }]},listaJogadores, 0) //0
    .slider({ "rawtext": [{ "translate": "admin.slider1" }]}, 0, 21, 1) //1
    .slider({ "rawtext": [{ "translate": "admin.slider2" }]}, 0, 30, 1) //2
    .toggle({ "rawtext": [{ "translate": "admin.toggle1" }]}) //3
	.toggle({ "rawtext": [{ "translate": "admin.toggle2" }]}) //4
	.toggle({ "rawtext": [{ "translate": "admin.toggle3" }]}) //5
	.textField({ "rawtext": [{ "translate": "admin.textField1" }]}, { "rawtext": [{ "translate": "admin.textField2" }]}); //6
	
	
        modal.show(player).then(reponse => {
			if (reponse.canceled) return
			
			
        	var tags = listaJogadores[reponse.formValues[0]]
            var quest = reponse.formValues[1]
            var subquest = reponse.formValues[2]
			var texto = reponse.formValues[6]
			
			
            if (reponse.formValues[3] == true) {
				player.runCommand(`tag ${tags} add punido`)
            	player.runCommand(`effect ${tags} clear`)
				player.runCommand(`effect ${tags} mining_fatigue 99999999 50 true`)
                player.runCommand(`effect ${tags} weakness 99999999 50 true`)
                player.runCommand(`inputpermission set ${tags} movement disabled`)
				player.runCommand(`tellraw @a { "rawtext": [{ "text": "${tags}"}, { "text": " "}, { "text": "§e"}, { "translate": "admin.congelar.player"}, { "text": "${texto}"}]}`)
				
				
            }
            if (reponse.formValues[3] == false) {
				player.runCommand(`tag ${tags} remove punido`)
				player.runCommand(`effect ${tags} mining_fatigue 0 50 true`)
                player.runCommand(`effect ${tags} weakness 0 100 true`)
                player.runCommand(`inputpermission set ${tags} movement enabled`)
				player.runCommand(`scoreboard players set ${tags} quest ${quest}`)
				player.runCommand(`scoreboard players set ${tags} subquest ${subquest}`)
            }
			if (reponse.formValues[4] == true) {
            	player.runCommand(`kick ${tags} ${texto}`)
				player.runCommand(`tellraw @a { "rawtext": [{ "text": "${tags}"}, { "text": " "}, { "text": "§e"}, { "translate": "admin.banir.player"}, { "text": "${texto}"}]}`)
				
            }
			if (reponse.formValues[5] == true) {
            	player.runCommand(`tp @s ${tags}`)
				player.runCommand(`tellraw @a { "rawtext": [{ "text": "${tags}"}, { "text": " "}, { "text": "§e"}, { "text": "${texto}"}]}`)
				
            }
			
			
			
			
			
			})} 
