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

const grabpackSoundState = new Map();

system.runInterval(() => {
    for (const player of world.getAllPlayers()) {

        const inventory = player.getComponent("minecraft:inventory");
        const container = inventory?.container;
        const item = container?.getItem(player.selectedSlotIndex);

        const isHoldingGrabpack =
            item?.typeId === "mebesm:grabpack_green_active" ||
            item?.typeId === "mebesm:grabpack_yellow_energi";

        const lastState = grabpackSoundState.get(player.id) || { holding: false, timer: 0 };

        if (isHoldingGrabpack) {

            if (!lastState.holding || lastState.timer <= 0) {

                player.runCommandAsync(`playsound electricity @a ~ ~ ~ 0.5 1`);

                lastState.timer = 40;

            } else {
                lastState.timer--;
            }

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

        } else {

            if (lastState.holding) {
                player.runCommandAsync(`stopsound @a electricity`);
            }

            grabpackSoundState.set(player.id, {
                holding: false,
                timer: 0
            });
        }
    }
}, 1);