import { EntityHealthComponent, system, world, EntityEquippableComponent, ItemDurabilityComponent, ItemStack, EquipmentSlot, EntityInventoryComponent } from "@minecraft/server";

world.beforeEvents.itemUse.subscribe(data => {
    let player = data.source
    let item = data.itemStack
    if (player.level >= 8 && item?.typeId == "fiery:mirror") {
        system.run(() => {
            player.addEffect("invisibility", 960, { amplifier: 0, showParticles: false });
            player.addLevels(-8);
            player.playSound("block.enchanting_table.use");
        })
    }
    if (player.level <= 8 && item?.typeId == "fiery:mirror") {
        system.run(() => {
            player.playSound("random.break");
            player.sendMessage("§cRequired §a8 experiences §cto use this ability!");
        })
    }
});

system.runInterval(() => {
    for (const player of world.getPlayers()) {
        const helmet = player.getComponent("equippable").getEquipment("Head");
        if (helmet == null) return;
        if (player.isOnGround && player.isSneaking == true && helmet.typeId === "fiery:cloak_of_invisibility") {
            const durabilityComponent = helmet.getComponent('durability');
            durabilityComponent.damage += 1;
            player.addEffect("invisibility", 60, { amplifier: 0, showParticles: false });
            //            player.addEffect("weakness", 10, { amplifier: 255, showParticles: false });
            //            helmet.setEquipment(EquipmentSlot.Head);
            if (durabilityComponent === 0) {
                helmet.setEquipment(EquipmentSlot.Head);
            }
        }
    }
}, 20);

system.runInterval(() => {
    for (const player of world.getPlayers()) {
        const playerEq = player.getComponent('equippable');
        const headEquipment = playerEq.getEquipment(EquipmentSlot.Head);
        if (!headEquipment || headEquipment.type.id !== 'btm:night_helmet') continue;
        const durabilityComponent = headEquipment.getComponent('durability');
        durabilityComponent.damage += 1;
        playerEq.setEquipment(EquipmentSlot.Head, headEquipment);
        if (durabilityComponent === 0) {
            playerEq.setEquipment(EquipmentSlot.Head);
        }
    }
}, 1);

world.afterEvents.entityHitEntity.subscribe((event) => {
    const { damagingEntity, hitEntity } = event;
    if (damagingEntity.getComponent('inventory').container.getItem(damagingEntity.selectedSlotIndex).typeId == 'fiery:double_stick') {
        hitEntity.applyKnockback(0, damagingEntity.getViewDirection().z, 0, 0.7)
    }
});

world.afterEvents.itemUse.subscribe(data => {
    const player = data.source;
    if (data.itemStack.typeId === `minecraft:`) {
        const look = player.getViewDirection();
        player.applyKnockback(look.x, look.z, 3, 0.5)
    }
});
