import { world } from "@minecraft/server";
import { toolDurability } from "../tool_durability.js";

world.afterEvents.itemReleaseUse.subscribe((event) => {
    const { itemStack, source, useDuration } = event;
    const { x, y, z } = source.getHeadLocation();
    const { x: xd, y: yd, z: zd } = source.getViewDirection();
    const inventory = source.getComponent("minecraft:inventory");

    if (itemStack?.typeId !== "sapphire_meteors:gravity_bow") return;

    if (source.getGameMode() !== "creative") {
        let arrowSlot = -1;
        let arrowItem = null;

        for (let i = 0; i < inventory.container.size; i++) {
            const item = inventory.container.getItem(i);
            if (item && item.typeId === "minecraft:arrow" && item.amount > 0) {
                arrowSlot = i;
                arrowItem = item;
                break;
            }
        }

        if (arrowSlot === -1) return;
        if (useDuration >= 71990) return;

        if (source.getGameMode() !== "creative") {
            if (arrowItem.amount > 1) {
                const newArrowItem = arrowItem.clone();
                newArrowItem.amount = arrowItem.amount - 1;
                inventory.container.setItem(arrowSlot, newArrowItem);
            }
            else {
                inventory.container.setItem(arrowSlot, undefined);
            }
        }
    }

    const projectile = source.dimension.spawnEntity("minecraft:arrow", { x: x, y: y + 0.15, z: z });
    const arrow = projectile.getComponent("minecraft:projectile");

    arrow.owner = source;
    source.addTag("sapphire_meteors:gravity_arrow");
    source.dimension.playSound("random.bow", source.getHeadLocation());
    arrow.shoot({ x: xd * 3.5, y: yd * 3.5, z: zd * 3.5 });
    
    // Reduce bow durability
    toolDurability(source, "Mainhand");
});

world.afterEvents.projectileHitEntity.subscribe((event) => {
    const { projectile, source } = event;
    const entity = event.getEntityHit().entity;
    if (!source.hasTag("sapphire_meteors:gravity_arrow")) return;
    source.removeTag("sapphire_meteors:gravity_arrow");

    if (projectile?.typeId !== "minecraft:arrow") return;
    if (entity?.getComponent("minecraft:type_family").hasTypeFamily("inanimate")) return;

    const selectedItem = source.getComponent("minecraft:equippable")?.getEquipment("Mainhand");
    if (selectedItem?.typeId !== "sapphire_meteors:gravity_bow") return;

    entity.addEffect("levitation", 100, { amplifier: 1, showParticles: false });
});