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

const soundState = new Map();

system.runInterval(() => {
    for (const player of world.getAllPlayers()) {
        const inventory = player.getComponent("inventory");
        const container = inventory?.container;
        const item = container?.getItem(player.selectedSlotIndex);

        const isHoldingChainsaw = item?.typeId === "mebesm:chainsaw_art";
        const lastState = soundState.get(player.id) || { holding: false, timer: 0 };

        if (isHoldingChainsaw) {
            if (!lastState.holding || lastState.timer <= 0) {
                // Изменено на 0.3 для тишины
                player.runCommand(`playsound art.chainsaw_general @a ~ ~ ~ 0.3 1`);
                lastState.timer = 95;
            } else {
                lastState.timer--;
            }

            if (system.currentTick % 8 === 0) {
                const entities = player.dimension.getEntities({
                    location: player.location,
                    maxDistance: 2.5,
                    excludeTypes: [
                        "minecraft:player",
                        "minecraft:item",
                        "minecraft:xp_orb",
                        "minecraft:arrow",
                        "minecraft:trident",
                        "minecraft:armor_stand",
                        "minecraft:minecart",
                        "minecraft:chest_minecart",
                        "minecraft:hopper_minecart",
                        "minecraft:tnt_minecart",
                        "minecraft:command_block_minecart",
                        "minecraft:boat",
                        "minecraft:chest_boat",
                        "minecraft:eye_of_ender_signal",
                        "minecraft:end_crystal",
                        "minecraft:firework_rocket",
                        "minecraft:shulker_bullet",
                        "minecraft:dragon_fireball",
                        "minecraft:small_fireball",
                        "minecraft:large_fireball",
                        "minecraft:thrown_trident"
                    ]
                });

                for (const entity of entities) {
                    try {
                        entity.applyDamage(5, { cause: "contact" });
                        player.dimension.spawnParticle("mebesm:blood", {
                            x: entity.location.x,
                            y: entity.location.y + 1.2,
                            z: entity.location.z
                        });
                    } catch (e) { }
                }
            }

            soundState.set(player.id, { holding: true, timer: lastState.timer });

        } else {
            if (lastState.holding) {
                player.runCommand(`stopsound @a art.chainsaw_general`);
                soundState.set(player.id, { holding: false, timer: 0 });
            }
        }
    }
}, 1);