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

const SCOREBOARD_NAME = "health";
const USE_TAG = "use";
const TAGGABLE_ITEMS = ["opm:basiccombat", "opm:prowess", "opm:trainingdummysummon", "opm:phone", "opm:genosability", "opm:limitlessessence", "opm:cyborgunlock", "opm:abilityremove", "opm:saitamaability", "opm:exerciseregime", "opm:saitamaunlock", "opm:garouability", "opm:garouunlock", "opm:gun",
    "opm:sonicability", "opm:sonicunlock", "opm:katana"]; // Add more items as needed

// Interval loop for health + creative tag
system.runInterval(() => {
    for (const player of world.getPlayers()) {
        try {
            // Update health scoreboard
            let healthComponent = player.getComponent("minecraft:health");
            let currentHealth = Math.floor(healthComponent?.currentValue ?? 0);
            player.runCommandAsync(`scoreboard players set @s ${SCOREBOARD_NAME} ${currentHealth}`);

            // Creative tag logic
            if (player.getGameMode() === "creative") {
                player.runCommandAsync(`tag @s add creative`);
            } else {
                player.runCommandAsync(`tag @s remove creative`);
            }
        } catch (error) {
            console.warn(`Error updating health or tags for ${player.name}: ${error}`);
        }
    }
}, 5);

// Tag player with "use" when they use a specified item
world.beforeEvents.itemUse.subscribe(event => {
    try {
        const { itemStack, source } = event;
        if (!source?.runCommandAsync || !itemStack?.typeId) return;

        if (TAGGABLE_ITEMS.includes(itemStack.typeId)) {
            // Tag the player immediately with "use"
            source.runCommandAsync(`tag @s[tag=!cutscene,tag=!stun] add ${USE_TAG}`);
        }
    } catch (error) {
        console.warn(`Error tagging item use: ${error}`);
    }
});