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

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

        // Find best potato: normal(2) > baked(1) > poisonous(0)
        let bestSlot = null;
        let bestPriority = -1;
        let isPoisonous = false;

        for (let i = 0; i < inventory.size; i++) {
            const it = inventory.getItem(i);
            if (!it) continue;

            let p = -1;
            if (it.typeId === "minecraft:potato") p = 2;
            else if (it.typeId === "minecraft:baked_potato") p = 1;
            else if (it.typeId === "minecraft:poisonous_potato") p = 0;

            if (p > bestPriority) {
                bestPriority = p;
                bestSlot = i;
                isPoisonous = (p === 0);
                if (p === 2) break;
            }
        }

        if (bestSlot === null) {
            player.runCommand(`titleraw @s actionbar {"rawtext":[{"text":"§cYou need a potato 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:potato_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.runCommand(`playsound random.bow @s ~~~ 1 0.3`);
            player.runCommand(`playsound random.bow @s ~~~ 0.05 1 0.01`);
        }

        if (isPoisonous) {
            proj.runCommand("event entity @s lv_zo:poisonous");
        }

        // Consume 1 potato
        {
            const used = inventory.getItem(bestSlot);
            if (used) {
                if (used.amount > 1) {
                    used.amount -= 1;
                    inventory.setItem(bestSlot, used);
                } else {
                    inventory.setItem(bestSlot, 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;

                    // Apply 2 damage rolls independently
                    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 PotatoLauncher;
