import { world, system } from "@minecraft/server";
import { levelMap } from "../logic/combatmastery.js";

const playerStamina = new Map();

function createStaminaBar(stamina, max_stamina) {
    const totalCubes = 8; 
    let filled = Math.floor((stamina / max_stamina) * totalCubes);
    let empty = 7 - filled;

    const startOn = "";  // A acceso
    const startOff = ""; // A spento
    const midOn = "";   // B acceso
    const midOff = "";  // B spento
    const lastMidOn = "";
    const lastMidOff = "";
    const endOn = "";   // C acceso
    const endOff = "";  // C spento


    const start = stamina > 0 ? startOn : startOff; 
    let mid = `${midOn.repeat(filled > 7 ? 7 : filled)}${midOff.repeat(empty < 0 ? 0 : empty)}`;


    const lastMid = ((stamina / max_stamina) * 100) >= 95 ? lastMidOn : lastMidOff;
    const end = stamina >= max_stamina ? endOn : endOff;

    return `${start}${mid}${lastMid}${end}`;
}

function createLevelBar(player) {
    const { exp, totalExp } = levelMap.get(player.id);
    const totalCubes = 8; 
    
    let filled = Math.floor((exp / totalExp) * totalCubes);
    const empty = 7 - filled;

    const startOn = "";  // A acceso
    const startOff = ""; // A spento
    const midOn = "";    // B acceso
    const midOff = "";   // B spento
    const lastMidOn = "";
    const lastMidOff = "";
    const endOn = "";    // C acceso
    const endOff = "";   // C spento

    const start = exp > 0 ? startOn : startOff; 
    let mid = `${midOn.repeat(filled > 7 ? 7 : filled)}${midOff.repeat(empty < 0 ? 0 : empty)}`;
    const lastMid = ((exp / totalExp) * 100) >= 95 ? lastMidOn : lastMidOff;

    const end = exp === totalExp ? endOn : endOff;

    return `${start}${mid}${lastMid}${end}`;
}


function sendActionbar(player, max_stamina) {
    const stamina = playerStamina.get(player.name);
    const staminaBar = createStaminaBar(stamina, max_stamina);
    const {level} = levelMap.get(player.id);
    const levelBar = createLevelBar(player);

    player.runCommand(`title @s actionbar ${levelBar} §8[ §7Lvl. §e${level} §8] ${staminaBar}`);
}

function updateStamina() {
    for (const player of world.getPlayers()) {

        const MAX_STAMINA = player.getDynamicProperty("max_stamina");
        const STAMINA_RECOVERY = player.getDynamicProperty("stamina_recovery");
        const STAMINA_CONSUMPTION_RUN = 2;

        if (!playerStamina.has(player.name)) {
            playerStamina.set(player.name, MAX_STAMINA);
        }

        const gameMode = player.getGameMode();
        if (gameMode === "creative" || gameMode == "spectator") {
            sendActionbar(player, MAX_STAMINA);
            continue;
        }

        const currentStamina = playerStamina.get(player.name);

        // if (currentStamina <= 10) {
        //     player.addEffect("minecraft:slowness", 9999, { amplifier: 5, showParticles: false });
        //     player.addTag("isExahust");
        //     soundNoMana(player, true);
        // } else {
        //     soundNoMana(player, false);
        //     player.removeEffect("minecraft:slowness");
        //     if (player.hasTag("isExahust")) player.removeTag("isExahust");
        // }



        let hasTag = player.getTags().some(tag => tag.startsWith("usingItem"));

        if (hasTag) continue;

        // Ensure STAMINA_RECOVERY is a valid number, default to 5 if undefined
        const recoveryRate = (STAMINA_RECOVERY !== undefined && STAMINA_RECOVERY !== null) ? STAMINA_RECOVERY : 5;
        
        // Regenerate stamina if it's below max (including when depleted at 0)
        if (currentStamina < MAX_STAMINA) {
            const newStamina = Math.min(currentStamina + recoveryRate, MAX_STAMINA);

            playerStamina.set(player.name, newStamina);
        }
        sendActionbar(player, MAX_STAMINA);
        }
    }

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

        const gameMode = player.getGameMode();
        if (gameMode === "creative" || gameMode == "spectator") continue;
        const currentStamina = playerStamina.get(player.name);

        if (currentStamina <= 10) {
            player.addEffect("minecraft:slowness", 9999, { amplifier: 5, showParticles: false });
            player.addTag("isExahust");
            player.playSound("msft:ability:fatigue");
        } else {
            player.removeEffect("minecraft:slowness");
            if (player.hasTag("isExahust")) player.removeTag("isExahust");
        }
    }
}, 40);

function modifyStamina(player, value, action) {

    const MAX_STAMINA = player.getDynamicProperty("max_stamina");
    const gameMode = player.getGameMode();
    if (gameMode === "creative" || gameMode == "spectator") {
        sendActionbar(player, player.getDynamicProperty("max_stamina"));
        return;
    }

    const currentStamina = playerStamina.get(player.name);
    let newStamina;
    if (action === "remove") {
        newStamina = Math.max(currentStamina - value, 0);
    } else if (action === "add") {
        newStamina = Math.min(currentStamina + value, MAX_STAMINA);
    }

    playerStamina.set(player.name, newStamina);
    sendActionbar(player, player.getDynamicProperty("max_stamina"));
}

system.runInterval(() => {
    updateStamina();
}, 20);

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

    if (event.damagingEntity.typeId != "minecraft:player") return;

    const entityHit = event.damagingEntity;
    const inv = entityHit.getComponent("minecraft:inventory").container;
    const heldItem = inv.getItem(entityHit.selectedSlotIndex);

    if (heldItem && heldItem.typeId.includes("battleaxe")) {
        const currentStamina = playerStamina.get(entityHit.nameTag);

        const newStamina = Math.max(currentStamina - 20, 0);

        playerStamina.set(entityHit.nameTag, newStamina);
        sendActionbar(entityHit, entityHit.getDynamicProperty("max_stamina"));
    }
})

world.afterEvents.playerJoin.subscribe((event) => {
    const player = world.getEntity(event.playerId);

    if (player.getDynamicProperty("max_stamina") === undefined) {
        player.setDynamicProperty("max_stamina", 80);
        player.setDynamicProperty("stamina_recovery", 5);
    }

    if (!playerStamina.has(event.playerName)) {
        const MAX_STAMINA = player.getDynamicProperty("max_stamina");

        playerStamina.set(event.playerName, MAX_STAMINA);
    }
})

export { modifyStamina, playerStamina };