import { world, system } from "@minecraft/server";
import * as utils from "../utils";
import * as Vector3 from "../vector3";

const COOLDOWN_CATEGORY = "wraith_reaper";
const COOLDOWN_DURATION = 60; // 60 ticks (3s)

export async function onItemUse(event) {
    const player = event.source;
    const cooldown = player.getItemCooldown(COOLDOWN_CATEGORY);
    if (cooldown > 0) return;

    // Disable player movement and camera
    player.inputPermissions.movementEnabled = false;
    player.inputPermissions.cameraEnabled = false;

    // Play third person animation
    utils.runPlayerCommand(player, `playanimation @s animation.goe_bos.player.wraith_reaper.attack.spin`);

    // Delay projectiles
    system.runTimeout(async () => {
        damageEntities(player);
    }, 7);

    system.runTimeout(async () => {
        damageEntities(player);
    }, 15);

    // Enable camera and movement
    system.runTimeout(() => {
        player.inputPermissions.movementEnabled = true;
        player.inputPermissions.cameraEnabled = true;
    }, 25);

    // Start cooldown
    player.startItemCooldown(COOLDOWN_CATEGORY, COOLDOWN_DURATION);

    damageHeldItem(player, 10);
}

async function damageEntities(player) {
    const entities = await utils.getAllEntitiesInRange(player.dimension, player.location, 0, 4);
        for (const entity of entities) {
            if (entity.id === player.id || entity.typeId === "minecraft:item")
                continue;

            entity.applyDamage(10, { cause: "magic", damagingEntity: player });
        }

        const particleLocation = player.location;
        particleLocation.y += 1;
        player.dimension.spawnParticle("goe_bos:scythe_slash", particleLocation);
        player.dimension.playSound("goe_bos:scythe_slash", player.location);
}

function damageHeldItem(player, amount = 1) {
    if (player.getGameMode() === "creative") return;
    
    const inventory = player.getComponent("minecraft:inventory").container;
    const selectedSlot = inventory.getSlot(player.selectedSlotIndex);
    const heldItem = selectedSlot.getItem();
    if (heldItem === undefined) return;

    const durabilityComponent = heldItem.getComponent("minecraft:durability");
    if (durabilityComponent === undefined) return;

    const itemDurability = durabilityComponent.maxDurability;
    durabilityComponent.damage += amount;

    if (durabilityComponent.damage === itemDurability) {
        selectedSlot.setItem(undefined);
        return;
    }

    selectedSlot.setItem(heldItem);
}