import { world, system } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";


world.afterEvents.playerInteractWithEntity.subscribe(event => {
    const { player, target } = event;
    if (!target || target.typeId !== "npc:npc_custom5") return;
    enchantedBooks(player);
});


world.afterEvents.entityHitEntity.subscribe(event => {
    const { damagingEntity, hitEntity } = event;
    if (!(damagingEntity?.typeId === "minecraft:player")) return;
    if (!hitEntity || hitEntity.typeId !== "npc:npc_custom5") return;
    enchantedBooks(damagingEntity);
});


function enchantedBooks(player) {
	player.playSound("random.pop2");
	player.playSound("mob.villager.haggle");
    let prices = [10, 500, 1000, 800]; // Prices: 4 Books, Mending, Wind Burst 1, Swift Sneak 1
    let structureNames = ["", "mending", "windburst", "swiftsneak"]; // Structure names for books
    let bookNames = ["4 Books", "Mending", "Wind Burst I", "Swift Sneak I"];

    function showForm() {
        
        let moneyObjective = world.scoreboard.getObjective("Money");
        let updatedScore = moneyObjective.getScore(player) ?? 0;

        let form = new ActionFormData()
            .title('§lThe Enchanter')
            .body(`Choose an enchanted book below!\nYour Current Amount of\n§aMoney: §a${updatedScore}`)
            .button('§l4 Books\n§rPrice = §a10', "textures/items/book_normal")
            .button('§lMending\n§rPrice = §a500', "textures/items/book")
            .button('§lWind Burst 1\n§rPrice = §a1000', "textures/items/book")
            .button('§lSwift Sneak 1\n§rPrice = §a800', "textures/items/book");

        form.show(player).then(response => {
            if (response.canceled) return;

            let selection = response.selection;

            
            updatedScore = moneyObjective.getScore(player) ?? 0;

            let itemPrice = prices[selection];

            if (updatedScore >= itemPrice) {
                player.runCommandAsync(`scoreboard players remove @s Money ${itemPrice}`);
                player.sendMessage(`§a${bookNames[selection]} Purchased Successfully!`);
                player.playSound("random.orb");

                if (selection === 0) {
                    player.runCommandAsync("give @s book 4"); // Give 4 normal books
                } else {
                    player.runCommandAsync(`execute at @s run structure load ${structureNames[selection]} ~~1~`);
                }

                
                system.runTimeout(() => showForm(), 1);
            } else {
                player.sendMessage("§cNot enough money!");
                player.playSound("mob.villager.no");
            }
        });
    }

    showForm(); // Call function to show UI
}