import {modifyStamina} from "../events/stamina"

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

world.afterEvents.itemCompleteUse.subscribe((event) => {

    const { itemStack, source } = event;
    if (!source || !itemStack) return;
    if (itemStack.typeId === "msft:small_stamina_potion") {
        const inventory = source.getComponent("minecraft:inventory")?.container;
        if (!inventory) return;


        let slotItem = inventory.getItem(0);
        if (slotItem && slotItem.typeId === itemStack.typeId) {
            if (slotItem.amount > 1) {
                slotItem.amount -= 1; 
                inventory.setItem(0, slotItem);
            } else {
                inventory.setItem(0, undefined); 
            }
        }

        const MAX_STAMINA = source.getDynamicProperty("max_stamina");
        const staminaAdd = 50;

        let location = {
            x: source.location.x + 1,
            y: source.location.y + 1.5,
            z: source.location.z
        }
        source.dimension.spawnParticle("msft_bc:consumable", location);
        
        source.playSound("msft:object:potion");
        if(staminaAdd > MAX_STAMINA) {
            modifyStamina(source, MAX_STAMINA, "add");
        } else {
            modifyStamina(source, staminaAdd, "add");
        }
    }
});
