import * as utils from "../utils.js";
import {system} from "@minecraft/server";

export async function onItemUse(event) {
    const player = event.source;
    const item = event.itemStack;
    if (item && item.typeId === "pu_sg:scifi_medkit") {
        if (!player.getDynamicProperty("pu_sg_scifi_medkit")) {
            player.setDynamicProperty("pu_sg_scifi_medkit", true);
            utils.runPlayerCommand(player, "effect @s slowness 2 1 true"); 
            // Define the max length of the bar
            const maxBarLength = 24;
            const barChar = "§a■"; // Change this character for a different look
            const emptyChar = "§f■"; // Change this character for an empty part of the bar
            const duration = 40; // Duration for the bar to fill in ticks (2 seconds)
            const interval = 2; // Update interval in ticks

            // Function to update the action bar
            let currentLength = 0;
            const updateBar = system.runInterval(() => {
                currentLength++;
                const filledLength = Math.floor((currentLength / (duration / interval)) * maxBarLength);
                const bar = `${barChar.repeat(filledLength)}${emptyChar.repeat(maxBarLength - filledLength)}`;
                player.onScreenDisplay.setActionBar(`§a${bar}`);
                
                // Check if the bar is filled
                if (currentLength >= duration / interval) {
                    system.clearRun(updateBar);

                    // Perform healing effect and particles
                    if (player.isValid()) {
                        const dimension = player.dimension;
                        const location = player.location;
                        utils.runPlayerCommand(player, "effect @s instant_health 1 3 true");
                        dimension.spawnParticle("pu_sg:scifi_medkit_1", location);
                        dimension.spawnParticle("pu_sg:scifi_medkit_2", location);
                        dimension.spawnParticle("pu_sg:scifi_medkit_3", location);
                        dimension.spawnParticle("pu_sg:scifi_medkit_4", location);
                        utils.runPlayerCommand(player, "clear @s pu_sg:scifi_medkit 0 1");
                        player.setDynamicProperty("pu_sg_scifi_medkit", false);
                        utils.runPlayerCommand(player, "effect @s slowness 0 0 true"); 
                        player.dimension.playSound("pu_sg:healing_bag_heal", player.location);
                    }
                }
            }, interval);
        }
    }
}
