import { EquipmentSlot, GameMode } from "@minecraft/server";

const SlimeSlingshot = {
    onUse(event) {
        const player = event.source;
        const equippable = player.getComponent("minecraft:equippable");
        const inventory = player.getComponent("inventory")?.container;
        if (!equippable || !inventory) return;

        // Find poisonous slime ammo
        let ammoSlot = null;
        for (let i = 0; i < inventory.size; i++) {
            const it = inventory.getItem(i);
            if (it?.typeId === "lv_zo:poisonous_slime") { ammoSlot = i; break; }
        }

        if (ammoSlot === null) {
            player.runCommand(`titleraw @s actionbar {"rawtext":[{"text":"§cYou need Poisonous Slime to fire!"}]}`);
            player.runCommand(`playsound note.bass @s ~~~ 0.4 1`);
            return;
        }

        // Fire projectile
        const dir = player.getViewDirection();
        const head = player.getHeadLocation();
        const spawnPos = { x: head.x + dir.x, y: head.y + dir.y, z: head.z + dir.z };
        const proj = player.dimension.spawnEntity("lv_zo:slime_projectile", spawnPos);
        const projComp = proj.getComponent("minecraft:projectile");

        if (projComp) {
            projComp.owner = player;
            projComp.shoot({ x: dir.x * 2, y: dir.y * 2, z: dir.z * 2 });
            player.playSound("lv_zo.slingshot", player.location);
        }

        // Consume 1 slime
        {
            const ammo = inventory.getItem(ammoSlot);
            if (ammo) {
                if (ammo.amount > 1) {
                    ammo.amount -= 1;
                    inventory.setItem(ammoSlot, ammo);
                } else {
                    inventory.setItem(ammoSlot, undefined);
                }
            }
        }

        // Durability: 2 points per shot (respect Unbreaking)
        if (player.getGameMode() !== GameMode.creative) {
            const main = equippable.getEquipmentSlot(EquipmentSlot.Mainhand);
            if (main?.hasItem()) {
                const stack = main.getItem();
                const dur = stack?.getComponent("minecraft:durability");
                if (dur) {
                    const ench = stack.getComponent("minecraft:enchantable");
                    const unbreakingLevel = ench?.getEnchantment("unbreaking")?.level ?? 0;

                    for (let i = 0; i < 2; i++) {
                        const chance = dur.getDamageChance(unbreakingLevel) / 100;
                        if (Math.random() <= chance) {
                            dur.damage++;
                        }
                    }

                    if (dur.damage >= dur.maxDurability) {
                        main.setItem(undefined);
                        player.playSound("random.break");
                    } else {
                        main.setItem(stack);
                    }
                }
            }
        }
    }
};

export default SlimeSlingshot;
