import { world, system, EntityDamageCause, EffectType } from "@minecraft/server";
import { modifyStamina } from "../stamina";

const doubleJumpCooldown = 100;
const doubleJumpWindow = 5;
let playerData = {};

system.runInterval(() => {

    for (const player of world.getAllPlayers()) {
        const id = player.id;

        if (!playerData[id]) {
            playerData[id] = {
                lastDoubleJumpTick: -doubleJumpCooldown,
                isWaitingForDoubleJump: false,
                jumpStartTime: 0,
                isJumping: false,
            };
        }
        const data = playerData[id];
        let now = system.currentTick;

        if (player.isJumping && !data.isJumping) {
            if (data.isWaitingForDoubleJump && now - data.jumpStartTime <= doubleJumpWindow) {
                if (now - data.lastDoubleJumpTick >= doubleJumpCooldown && !player.hasTag("useSkill")) {
                    player.addTag("useSkill");

                    if (player.hasTag("isExahust")) {
                        player.playSound("msft:ambient:no-mana");
                        player.removeTag("useSkill");
                        continue;
                    }
                    executeDoubleJump(player);
                    data.lastDoubleJumpTick = now;
                } else {
                    world.sendMessage(`§c${player.name} double jump is on cooldown!`);
                }
                data.isWaitingForDoubleJump = false;
            } else {
                data.jumpStartTime = now;
                data.isWaitingForDoubleJump = true;

                system.runTimeout(() => {
                    if (data.isWaitingForDoubleJump) {
                        modifyStamina(player, 5, "remove");
                        data.isWaitingForDoubleJump = false;
                    }
                }, doubleJumpWindow);
            }
        }

        data.isJumping = player.isJumping;
    }
}, 1);

function executeDoubleJump(player) {
    player.addTag("is_double_jumping");

    player.applyKnockback(0, 0, 1.8, 1);
    player.playSound("msft:ability:jump");
    
    player.removeTag("useSkill");

    modifyStamina(player, 15, "remove");

    system.runTimeout(() => {
        player.addEffect("minecraft:slow_falling", 20, { showParticles: false });
    }, 20); 

    system.runTimeout(() => {
        player.removeTag("is_double_jumping");
    }, 10);
}