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_custom4") return;
    shopui(player);
    player.playSound("random.pop2");
    player.playSound("mob.villager.haggle");
});


world.afterEvents.entityHitEntity.subscribe(event => {
    const { damagingEntity, hitEntity } = event;
    if (!(damagingEntity?.typeId === "minecraft:player")) return;
    if (!hitEntity || hitEntity.typeId !== "npc:npc_custom4") return;
    shopui(damagingEntity);
    damagingEntity.playSound("random.pop2");
    damagingEntity.playSound("mob.villager.haggle");
});

function shopui(player) {
    new ActionFormData()
        .title('§lThe Merchant')
        .body('Choose an option below!')
        .button('Tools\n§r§7[ Click to View ]', "textures/items/iron_pickaxe")
        .button('Weapons\n§r§7[ Click to View ]', "textures/items/iron_sword")
        .button('Armors\n§r§7[ Click to View ]', "textures/items/iron_chestplate")
        .button('Armor Trims\n§r§7[ Click to View ]', "textures/items/wayfinder_armor_trim_smithing_template")
        .button('Projectiles\n§r§7[ Click to View ]', "textures/items/bow_standby")
        .button('Healings\n§r§7[ Click to View ]', "textures/ui/heart")
        .button('Foods\n§r§7[ Click to View ]', "textures/items/apple")
        .button('Other Items\n§r§7[ Click to View ]', "textures/items/chest")
        .button('Music Disc\n§r§7[ Click to View ]', "textures/items/music_disc_13")
        .show(player).then(r => {
            if (r.selection == 0) tools(player);
            if (r.selection == 1) weapons(player);
            if (r.selection == 2) armors(player);
            if (r.selection == 3) armortrim(player);
            if (r.selection == 4) projectiles(player);
            if (r.selection == 5) healings(player);
            if (r.selection == 6) foods(player);
            if (r.selection == 7) others(player);
            if (r.selection == 8) musicDiscShop(player);
        });
}

function musicDiscShop(player) {
    const tags = player.getTags();
    const rankDiscounts = {
        "gwim:God":       { rank: "GOD", discount: 1.0 },
        "gwim:ElitePlus": { rank: "Elite+", discount: 1.0 },
        "gwim:Elite":     { rank: "Elite", discount: 0.8 },
        "gwim:VIPPlus":   { rank: "VIP+", discount: 0.6 },
        "gwim:VIP":       { rank: "VIP", discount: 0.4 }
    };

    let discount = 0;
    let rankName = "None";
    for (const tag in rankDiscounts) {
        if (tags.includes(tag)) {
            discount = rankDiscounts[tag].discount;
            rankName = rankDiscounts[tag].rank;
            break;
        }
    }

    const prices = [
        800, 850, 900, 950, 1000, 1100, 1150,
        1200, 1250, 1300, 1350, 1400, 1450,
        1500, 1550, 1600, 1650, 1700, 1750,
        1800, 1900
    ];

    const discs = [
        "music_disc_13", "music_disc_cat", "music_disc_blocks", "music_disc_chirp", "music_disc_far",
        "music_disc_mall", "music_disc_mellohi", "music_disc_stal", "music_disc_strad", "music_disc_ward",
        "music_disc_11", "music_disc_wait", "music_disc_pigstep", "music_disc_otherside", "music_disc_5",
        "music_disc_relic", "music_disc_precipice", "music_disc_tears", "music_disc_creator",
        "music_disc_creator_music_box", "music_disc_lava_chicken"
    ];

    const discNames = [
        "13", "Cat", "Blocks", "Chirp", "Far", "Mall", "Mellohi", "Stal", "Strad", "Ward",
        "11", "Wait", "Pigstep", "Otherside", "5", "Relic", "Precipice", "Tears",
        "Creator", "Creator (Music Box)", "Lava Chicken"
    ];

    const discountedPrices = prices.map(p => Math.floor(p * (1 - discount)));
    const moneyObjective = world.scoreboard.getObjective("Money");

    function showForm() {
        const currentMoney = moneyObjective.getScore(player) ?? 0;

        const form = new ActionFormData()
            .title("§lMusic Disc")
            .body(`Choose a Music Disc below!\n§7Your Rank: §b§l${rankName}§r\n§7Discount: §a${Math.floor(discount * 100)}%\n§7Money: §a$${currentMoney}`);

        for (let i = 0; i < discs.length; i++) {
            form.button(`§l${discNames[i]}\n§rPrice = §a$${discountedPrices[i]}`, `textures/items/${discs[i]}`);
        }

        form.button("§l§cBack", "textures/ui/arrow_left");

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

            const selection = res.selection;
            if (selection === discs.length) return shopui(player); // back

            const selectedDisc = discs[selection];
            const cost = discountedPrices[selection];
            const displayName = discNames[selection];
            const playerMoney = moneyObjective.getScore(player) ?? 0;

            if (playerMoney >= cost) {
                player.runCommandAsync(`scoreboard players remove @s Money ${cost}`);
                player.runCommandAsync(`give @s ${selectedDisc}`);
                player.sendMessage(`§aMusic Disc "${displayName}" purchased successfully!`);
                player.playSound("random.orb");

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

    showForm();
}

function tools(player) {
    const tags = player.getTags();
    const rankDiscounts = {
        "gwim:God": { rank: "GOD", discount: 1.0 },
        "gwim:ElitePlus": { rank: "Elite+", discount: 1.0 },
        "gwim:Elite":     { rank: "Elite", discount: 0.8 },
        "gwim:VIPPlus":   { rank: "VIP+", discount: 0.6 },
        "gwim:VIP":       { rank: "VIP", discount: 0.4 }
    };

    let discount = 0;
    let rankName = "None";

    for (const tag in rankDiscounts) {
        if (tags.includes(tag)) {
            discount = rankDiscounts[tag].discount;
            rankName = rankDiscounts[tag].rank;
            break;
        }
    }
    
    // Updated prices and items with axes before shovels
let prices = [
    0, 300, 250, 3800, 25899, // Pickaxes
    15, 280, 220, 3600, 25000, // Axes
    10, 200, 125, 2000, 16000  // Shovels
];

let items = [
    "wooden_pickaxe", "stone_pickaxe", "golden_pickaxe", "iron_pickaxe", "diamond_pickaxe",
    "wooden_axe", "stone_axe", "golden_axe", "iron_axe", "diamond_axe",
    "wooden_shovel", "stone_shovel", "golden_shovel", "iron_shovel", "diamond_shovel"
];

    let discountedPrices = prices.map(p => Math.floor(p * (1 - discount)));

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

        let form = new ActionFormData()
            .title('§lTools')
            .body(`Choose a Tool below!\n§7Your Rank: §b§l${rankName}§r\n§7Discount: §a${Math.floor(discount * 100)}%\n§7Money: §a$${updatedScore}`)
            
            // Pickaxes
            .button(`§lWooden Pickaxe\n§rPrice = §a${discountedPrices[0]}`, "textures/items/wood_pickaxe")
            .button(`§lStone Pickaxe\n§rPrice = §a${discountedPrices[1]}`, "textures/items/stone_pickaxe")
            .button(`§lGolden Pickaxe\n§rPrice = §a${discountedPrices[2]}`, "textures/items/gold_pickaxe")
            .button(`§lIron Pickaxe\n§rPrice = §a${discountedPrices[3]}`, "textures/items/iron_pickaxe")
            .button(`§lDiamond Pickaxe\n§rPrice = §a${discountedPrices[4]}`, "textures/items/diamond_pickaxe")
            
            // Axes
            .button(`§lWooden Axe\n§rPrice = §a${discountedPrices[5]}`, "textures/items/wood_axe")
            .button(`§lStone Axe\n§rPrice = §a${discountedPrices[6]}`, "textures/items/stone_axe")
            .button(`§lGolden Axe\n§rPrice = §a${discountedPrices[7]}`, "textures/items/gold_axe")
            .button(`§lIron Axe\n§rPrice = §a${discountedPrices[8]}`, "textures/items/iron_axe")
            .button(`§lDiamond Axe\n§rPrice = §a${discountedPrices[9]}`, "textures/items/diamond_axe")
            
            // Shovels
            .button(`§lWooden Shovel\n§rPrice = §a${discountedPrices[10]}`, "textures/items/wood_shovel")
            .button(`§lStone Shovel\n§rPrice = §a${discountedPrices[11]}`, "textures/items/stone_shovel")
            .button(`§lGolden Shovel\n§rPrice = §a${discountedPrices[12]}`, "textures/items/gold_shovel")
            .button(`§lIron Shovel\n§rPrice = §a${discountedPrices[13]}`, "textures/items/iron_shovel")
            .button(`§lDiamond Shovel\n§rPrice = §a${discountedPrices[14]}`, "textures/items/diamond_shovel")
            
            .button('§l§cBack', "textures/ui/arrow_left");

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

            let selection = response.selection;
            if (selection === 15) return shopui(player); // Back button (now at index 15)

            updatedScore = moneyObjective.getScore(player) ?? 0;
            let itemPrice = discountedPrices[selection];
            let itemName = items[selection];

            let formattedName = itemName.replace(/_/g, ' ')
    .replace(/\bpickaxe\b/gi, 'Pickaxe')
    .replace(/\bshovel\b/gi, 'Shovel')
    .replace(/\baxe\b/gi, 'Axe')
    .split(' ')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');

            if (updatedScore >= itemPrice) {
                player.runCommandAsync(`scoreboard players remove @s Money ${itemPrice}`);
                player.runCommandAsync(`give @s ${itemName} 1`);
                player.sendMessage(`§a${formattedName} Purchased Successfully!`);
                player.playSound("random.orb");

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

    showForm();
}


function weapons(player) {
    const tags = player.getTags();
    const rankDiscounts = {
        "gwim:God": { rank: "GOD", discount: 1.0 },
        "gwim:ElitePlus": { rank: "Elite+", discount: 1.0 },
        "gwim:Elite":     { rank: "Elite", discount: 0.8 },
        "gwim:VIPPlus":   { rank: "VIP+", discount: 0.6 },
        "gwim:VIP":       { rank: "VIP", discount: 0.4 }
    };

    let discount = 0;
    let rankName = "None";

    for (const tag in rankDiscounts) {
        if (tags.includes(tag)) {
            discount = rankDiscounts[tag].discount;
            rankName = rankDiscounts[tag].rank;
            break;
        }
    }

    let prices = [0, 285, 230, 4100, 26000, 51000]; // Removed netherite sword
    let items = [
        "wooden_sword", "stone_sword", "golden_sword", "iron_sword", "diamond_sword", "mace"
    ];
    let discountedPrices = prices.map(p => Math.floor(p * (1 - discount)));

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

        let form = new ActionFormData()
            .title('§lWeapons')
            .body(`Choose a Weapon below!\n§7Your Rank: §b§l${rankName}§r\n§7Discount: §a${Math.floor(discount * 100)}%\n§7Money: §a$${updatedScore}`)
            .button(`§lWooden Sword\n§rPrice = §a${discountedPrices[0]}`, "textures/items/wood_sword")
            .button(`§lStone Sword\n§rPrice = §a${discountedPrices[1]}`, "textures/items/stone_sword")
            .button(`§lGolden Sword\n§rPrice = §a${discountedPrices[2]}`, "textures/items/gold_sword")
            .button(`§lIron Sword\n§rPrice = §a${discountedPrices[3]}`, "textures/items/iron_sword")
            .button(`§lDiamond Sword\n§rPrice = §a${discountedPrices[4]}`, "textures/items/diamond_sword")
            .button(`§lMace\n§rPrice = §a${discountedPrices[5]}`, "textures/items/mace")
            .button('§l§cBack', "textures/ui/arrow_left");

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

            let selection = response.selection;
            if (selection === 6) return shopui(player); // Back button (new index)

            let itemPrice = discountedPrices[selection];
            let itemName = items[selection];

            let formattedName = itemName.replace('_', ' ').replace('sword', 'Sword').replace('mace', 'Mace');
            formattedName = formattedName.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');

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

            if (updatedScore >= itemPrice) {
                player.runCommandAsync(`scoreboard players remove @s Money ${itemPrice}`);
                player.runCommandAsync(`give @s ${itemName} 1`);
                player.sendMessage(`§a${formattedName} Purchased Successfully!`);
                player.playSound("random.orb");
                system.runTimeout(() => showForm(), 1);
            } else {
                player.sendMessage("§cNot enough money!");
                player.playSound("note.bass");
            }
        });
    }

    showForm();
}

function armors(player) {
    const tags = player.getTags();
    const rankDiscounts = {
        "gwim:God": { rank: "GOD", discount: 1.0 },
        "gwim:ElitePlus": { rank: "Elite+", discount: 1.0 },
        "gwim:Elite":     { rank: "Elite", discount: 0.8 },
        "gwim:VIPPlus":   { rank: "VIP+", discount: 0.6 },
        "gwim:VIP":       { rank: "VIP", discount: 0.4 }
    };

    let discount = 0;
    let rankName = "None";

    for (const tag in rankDiscounts) {
        if (tags.includes(tag)) {
            discount = rankDiscounts[tag].discount;
            rankName = rankDiscounts[tag].rank;
            break;
        }
    }

    let prices = [
        0, 0, 0, 0, 950, 7480, 9699, 8300, 7000, 
        570, 698, 610, 500, 31100, 36000, 35525, 30999
    ];
    let items = [
        "leather_helmet", "leather_chestplate", "leather_leggings", "leather_boots",
        "turtle_helmet", "iron_helmet", "iron_chestplate", "iron_leggings", "iron_boots",
        "golden_helmet", "golden_chestplate", "golden_leggings", "golden_boots",
        "diamond_helmet", "diamond_chestplate", "diamond_leggings", "diamond_boots"
    ];

    let discountedPrices = prices.map(p => Math.floor(p * (1 - discount)));

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

        let form = new ActionFormData()
            .title('§lArmors')
            .body(`Choose an Armor piece below!\n§7Your Rank: §b§l${rankName}§r\n§7Discount: §a${Math.floor(discount * 100)}%\n§7Money: §a$${updatedScore}`)
            .button(`§lLeather Helmet\n§rPrice = §a${discountedPrices[0]}`, "textures/items/leather_helmet")
            .button(`§lLeather Chestplate\n§rPrice = §a${discountedPrices[1]}`, "textures/items/leather_chestplate")
            .button(`§lLeather Leggings\n§rPrice = §a${discountedPrices[2]}`, "textures/items/leather_leggings")
            .button(`§lLeather Boots\n§rPrice = §a${discountedPrices[3]}`, "textures/items/leather_boots")
            .button(`§lTurtle Helmet\n§rPrice = §a${discountedPrices[4]}`, "textures/items/turtle_helmet")
            .button(`§lIron Helmet\n§rPrice = §a${discountedPrices[5]}`, "textures/items/iron_helmet")
            .button(`§lIron Chestplate\n§rPrice = §a${discountedPrices[6]}`, "textures/items/iron_chestplate")
            .button(`§lIron Leggings\n§rPrice = §a${discountedPrices[7]}`, "textures/items/iron_leggings")
            .button(`§lIron Boots\n§rPrice = §a${discountedPrices[8]}`, "textures/items/iron_boots")
            .button(`§lGolden Helmet\n§rPrice = §a${discountedPrices[9]}`, "textures/items/gold_helmet")
            .button(`§lGolden Chestplate\n§rPrice = §a${discountedPrices[10]}`, "textures/items/gold_chestplate")
            .button(`§lGolden Leggings\n§rPrice = §a${discountedPrices[11]}`, "textures/items/gold_leggings")
            .button(`§lGolden Boots\n§rPrice = §a${discountedPrices[12]}`, "textures/items/gold_boots")
            .button(`§lDiamond Helmet\n§rPrice = §a${discountedPrices[13]}`, "textures/items/diamond_helmet")
            .button(`§lDiamond Chestplate\n§rPrice = §a${discountedPrices[14]}`, "textures/items/diamond_chestplate")
            .button(`§lDiamond Leggings\n§rPrice = §a${discountedPrices[15]}`, "textures/items/diamond_leggings")
            .button(`§lDiamond Boots\n§rPrice = §a${discountedPrices[16]}`, "textures/items/diamond_boots")
            .button('§l§cBack', "textures/ui/arrow_left");

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

            let selection = response.selection;
            if (selection === 17) return shopui(player); // Back button (new index)

            let itemPrice = discountedPrices[selection];
            let itemName = items[selection];
            let formattedName = itemName.replace('_', ' ').replace('helmet', 'Helmet')
                .replace('chestplate', 'Chestplate').replace('leggings', 'Leggings')
                .replace('boots', 'Boots');
            formattedName = formattedName.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');

            if (updatedScore >= itemPrice) {
                player.runCommandAsync(`scoreboard players remove @s Money ${itemPrice}`);
                player.runCommandAsync(`give @s ${itemName} 1`);
                player.sendMessage(`§a${formattedName} Purchased Successfully!`);
                player.playSound("random.orb");
                system.runTimeout(() => showForm(), 1);
            } else {
                player.sendMessage("§cNot enough money!");
                player.playSound("note.bass");
            }
        });
    }

    showForm();
}


function projectiles(player) {
    const tags = player.getTags();
    const rankDiscounts = {
    	"gwim:God": { rank: "GOD", discount: 1.0 },
        "gwim:ElitePlus": { rank: "Elite+", discount: 1.0 },
        "gwim:Elite":     { rank: "Elite", discount: 0.8 },
        "gwim:VIPPlus":   { rank: "VIP+", discount: 0.6 },
        "gwim:VIP":       { rank: "VIP", discount: 0.4 }
    };

    let discount = 0;
    let rankName = "None";

    for (const tag in rankDiscounts) {
        if (tags.includes(tag)) {
            discount = rankDiscounts[tag].discount;
            rankName = rankDiscounts[tag].rank;
            break;
        }
    }

    let prices = [6500, 5000, 60, 250, 100, 21899, 160, 80];
    let items = [
        "bow 1",
        "crossbow 1",
        "arrow 4",
        "fireball 6",
        "firework_rocket 6",
        "trident 1",
        "wind_charge 6",
        "snowball 8"
    ];

    let discountedPrices = prices.map(p => Math.floor(p * (1 - discount)));

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

        let form = new ActionFormData()
            .title('§lProjectiles')
            .body(`Choose a projectile item below!\n§7Your Rank: §l§b${rankName}§r\n§7Discount: §a${Math.floor(discount * 100)}%\n§7Money: §a$${updatedScore}`)
            .button(`§lBow\n§rPrice = §a${discountedPrices[0]}`, "textures/items/bow_standby")
            .button(`§lCrossbow\n§rPrice = §a${discountedPrices[1]}`, "textures/items/crossbow_standby")
            .button(`§l4 Arrows\n§rPrice = §a${discountedPrices[2]}`, "textures/items/arrow")
            .button(`§l6 Fireballs\n§rPrice = §a${discountedPrices[3]}`, "textures/items/fireball")
            .button(`§l6 Firework Rockets\n§rPrice = §a${discountedPrices[4]}`, "textures/items/firework_rocket")
            .button(`§lTrident\n§rPrice = §a${discountedPrices[5]}`, "textures/items/trident")
            .button(`§l6 Wind Charges\n§rPrice = §a${discountedPrices[6]}`, "textures/items/wind_charge")
            .button(`§l8 Snowballs\n§rPrice = §a${discountedPrices[7]}`, "textures/items/snowball")
            .button('§l§cBack', "textures/ui/arrow_left");

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

            let selection = response.selection;
            if (selection === 8) return shopui(player); // Back button

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

            let itemPrice = discountedPrices[selection];
            let itemData = items[selection];
            let [item, quantity] = itemData.split(' ');
            quantity = parseInt(quantity);

            let formattedName = item.replace(/_/g, ' ').replace(/\b\w/g, char => char.toUpperCase());
            let successMessage = quantity > 1 ? `${quantity} ${formattedName}s` : `${formattedName}`;

            if (updatedScore >= itemPrice) {
                player.runCommandAsync(`scoreboard players remove @s Money ${itemPrice}`);
                player.runCommandAsync(`give @s ${item} ${quantity}`);
                player.sendMessage(`§a${successMessage} Purchased Successfully!`);
                player.playSound("random.orb");

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

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


function healings(player) {
    const tags = player.getTags();
    const rankDiscounts = {
    	"gwim:God": { rank: "GOD", discount: 1.0 },
        "gwim:ElitePlus": { rank: "Elite+", discount: 1.0 },
        "gwim:Elite":     { rank: "Elite", discount: 0.8 },
        "gwim:VIPPlus":   { rank: "VIP+", discount: 0.6 },
        "gwim:VIP":       { rank: "VIP", discount: 0.4 }
    };

    let discount = 0;
    let rankName = "None";

    for (const tag in rankDiscounts) {
        if (tags.includes(tag)) {
            discount = rankDiscounts[tag].discount;
            rankName = rankDiscounts[tag].rank;
            break;
        }
    }

    let prices = [
        200, 250, 100, 200, 130, 110,
        5879, 22990, 23540
    ];
    let items = [
        "potion 1 22", "potion 1 30", "potion 1 16", "potion 1 33", "potion 1 13", "potion 1 41",
        "golden_apple 4", "enchanted_golden_apple 2", "totem_of_undying 2"
    ];
    let discountedPrices = prices.map(p => Math.floor(p * (1 - discount)));

    let potionNames = {
        "22": "Instant Health Potion",
        "30": "Regeneration Potion",
        "16": "Swiftness Potion",
        "33": "Strength Potion",
        "13": "Fire Resistance Potion",
        "41": "Slow Falling Potion"
    };

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

        let form = new ActionFormData()
            .title('§lHealings')
            .body(`Choose a healing item below!\n§7Your Rank: §b§l${rankName}§r\n§7Discount: §a${Math.floor(discount * 100)}%\n§7Money: §a$${updatedScore}`)
            .button(`§lInstant Health Potion\n§rPrice = §a${discountedPrices[0]}`, "textures/items/potion_bottle_heal")
            .button(`§lRegeneration Potion\n§rPrice = §a${discountedPrices[1]}`, "textures/items/potion_bottle_regeneration")
            .button(`§lSwiftness Potion\n§rPrice = §a${discountedPrices[2]}`, "textures/items/potion_bottle_speed")
            .button(`§lStrength Potion\n§rPrice = §a${discountedPrices[3]}`, "textures/items/potion_bottle_strength")
            .button(`§lFire Resistance Potion\n§rPrice = §a${discountedPrices[4]}`, "textures/items/potion_bottle_fire_resistance")
            .button(`§lSlow Falling Potion\n§rPrice = §a${discountedPrices[5]}`, "textures/items/potion_bottle_slow_falling")
            .button(`§l4 Golden Apples\n§rPrice = §a${discountedPrices[6]}`, "textures/items/apple_golden")
            .button(`§l2 Notch Apples\n§rPrice = §a${discountedPrices[7]}`, "textures/items/enchanted_golden_apple")
            .button(`§l2 Totems of Undying\n§rPrice = §a${discountedPrices[8]}`, "textures/items/totem")
            .button('§l§cBack', "textures/ui/arrow_left");

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

            let selection = response.selection;
            if (selection === 9) return shopui(player); // Back button

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

            let itemPrice = discountedPrices[selection];
            let itemData = items[selection];

            let [item, quantity, potionEffect] = itemData.split(' ');
            quantity = parseInt(quantity, 10);

            let formattedName = item === "potion"
                ? potionNames[potionEffect] ?? "Unknown Potion"
                : item.replace(/_/g, ' ').replace(/\b\w/g, char => char.toUpperCase());

            let successMessage = quantity > 1 ? `${quantity} ${formattedName}s` : `${formattedName}`;

            if (updatedScore >= itemPrice) {
                player.runCommandAsync(`scoreboard players remove @s Money ${itemPrice}`);
                if (item === "potion") {
                    player.runCommandAsync(`give @s potion ${quantity} ${potionEffect}`);
                } else {
                    player.runCommandAsync(`give @s ${item} ${quantity}`);
                }
                player.sendMessage(`§a${successMessage} Purchased Successfully!`);
                player.playSound("random.orb");

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

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


function foods(player) {
    const tags = player.getTags();
    const rankDiscounts = {
    	"gwim:God": { rank: "GOD", discount: 1.0 },
        "gwim:ElitePlus": { rank: "Elite+", discount: 1.0 },
        "gwim:Elite":     { rank: "Elite", discount: 0.8 },
        "gwim:VIPPlus":   { rank: "VIP+", discount: 0.6 },
        "gwim:VIP":       { rank: "VIP", discount: 0.4 }
    };

    let discount = 0;
    let rankName = "None";

    for (const tag in rankDiscounts) {
        if (tags.includes(tag)) {
            discount = rankDiscounts[tag].discount;
            rankName = rankDiscounts[tag].rank;
            break;
        }
    }

    let prices = [
        0, 5, 10, 15, 25, 35, 50,
        75, 80, 10, 15, 130, 150, 140, 25, 110, 50
    ];
    let items = [
        "dried_kelp 16",
        "glow_berries 8",
        "bread 8",
        "baked_potato 6",
        "cooked_chicken 10",
        "cooked_mutton 12",
        "cooked_porkchop 1",
        "cooked_beef 15", 
        "cooked_rabbit 15", 
        "beetroot_soup 2", 
        "rabbit_stew 2",
        "pumpkin_pie 8", 
        "golden_carrot 10",
        "cooked_cod 12",  
        "mushroom_stew 2",   
        "cooked_salmon 16",    
        "cookie 10"  
    ];
    let discountedPrices = prices.map(p => Math.floor(p * (1 - discount)));

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

        let form = new ActionFormData()
            .title('§lFoods')
            .body(`Choose food items below!\n§7Your Rank: §b§l${rankName}§r\n§7Discount: §a${Math.floor(discount * 100)}%\n§7Money: §a$${updatedScore}`)
            .button(`§l16 Dried Kelp\n§rPrice = §a${discountedPrices[0]}`, "textures/items/dried_kelp")
            .button(`§l8 Glow Berries\n§rPrice = §a${discountedPrices[1]}`, "textures/items/glow_berries")  
            .button(`§l8 Bread\n§rPrice = §a${discountedPrices[2]}`, "textures/items/bread")
            .button(`§l6 Baked Potatoes\n§rPrice = §a${discountedPrices[3]}`, "textures/items/potato_baked")
            .button(`§l10 Cooked Chicken\n§rPrice = §a${discountedPrices[4]}`, "textures/items/chicken_cooked")
            .button(`§l12 Cooked Mutton\n§rPrice = §a${discountedPrices[5]}`, "textures/items/mutton_cooked")
            .button(`§l1 Cooked Porkchop\n§rPrice = §a${discountedPrices[6]}`, "textures/items/porkchop_cooked")
            .button(`§l15 Cooked Beef\n§rPrice = §a${discountedPrices[7]}`, "textures/items/beef_cooked")
            .button(`§l15 Cooked Rabbit\n§rPrice = §a${discountedPrices[8]}`, "textures/items/rabbit_cooked")
            .button(`§l2 Beetroot Soup\n§rPrice = §a${discountedPrices[9]}`, "textures/items/beetroot_soup")
            .button(`§l2 Rabbit Stew\n§rPrice = §a${discountedPrices[10]}`, "textures/items/rabbit_stew")
            .button(`§l8 Pumpkin Pie\n§rPrice = §a${discountedPrices[11]}`, "textures/items/pumpkin_pie")
            .button(`§l10 Golden Carrots\n§rPrice = §a${discountedPrices[12]}`, "textures/items/carrot_golden")
            .button(`§l12 Cooked Cod\n§rPrice = §a${discountedPrices[13]}`, "textures/items/fish_cooked")  
            .button(`§l2 Mushroom Stew\n§rPrice = §a${discountedPrices[14]}`, "textures/items/mushroom_stew")  
            .button(`§l16 Cooked Salmon\n§rPrice = §a${discountedPrices[15]}`, "textures/items/fish_salmon_cooked")  
            .button(`§l10 Cookies\n§rPrice = §a${discountedPrices[16]}`, "textures/items/cookie")  
            .button('§l§cBack', "textures/ui/arrow_left");

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

            let selection = response.selection;
            if (selection === 17) return shopui(player); // Back button

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

            let itemPrice = discountedPrices[selection];
            let itemData = items[selection];

            let [item, quantity] = itemData.split(' ');
            quantity = parseInt(quantity, 10);

            let formattedName = item.replace(/_/g, ' ').replace(/\b\w/g, char => char.toUpperCase());
            let successMessage = `${quantity} ${formattedName}${quantity > 1 ? 's' : ''}`;

            if (updatedScore >= itemPrice) {
                player.runCommandAsync(`scoreboard players remove @s Money ${itemPrice}`);
                player.runCommandAsync(`give @s ${item} ${quantity}`);
                player.sendMessage(`§a${successMessage} Purchased Successfully!`);
                player.playSound("random.orb");

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

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


function others(player) {
    const tags = player.getTags();
    const rankDiscounts = {
    	"gwim:God": { rank: "GOD", discount: 1.0 },
        "gwim:ElitePlus": { rank: "Elite+", discount: 1.0 },
        "gwim:Elite":     { rank: "Elite", discount: 0.8 },
        "gwim:VIPPlus":   { rank: "VIP+", discount: 0.6 },
        "gwim:VIP":       { rank: "VIP", discount: 0.4 }
    };

    let discount = 0;
    let rankName = "None";

    for (const tag in rankDiscounts) {
        if (tags.includes(tag)) {
            discount = rankDiscounts[tag].discount;
            rankName = rankDiscounts[tag].rank;
            break;
        }
    }

    let prices = [
        1000, 2000, 1250, 18000, 32, 37500, 100, 300, 3500,
        16, 100, 350
    ];

    let items = [
        "compass 1",
        "pa:plot 1", // Plot Management placeholder
        "shield 1",
        "netherite_ingot 1",
        "torch 16",
        "elytra 1",
        "firework_rocket 6",
        "bundle 1",
        "shulker_box 1",
        "experience_bottle 8",
        "spyglass 1",
        "fishing_rod 1"
    ];

    let discountedPrices = prices.map(p => Math.floor(p * (1 - discount)));

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

        let form = new ActionFormData()
            .title('§lOther Items')
            .body(`Choose an item below!\n§7Your Rank: §b§l${rankName}§r\n§7Discount: §a${Math.floor(discount * 100)}%\n§7Money: §a$${updatedScore}`)
            .button(`§lQuick Teleporter\n§rPrice = §a${discountedPrices[0]}`, "textures/items/compass_item")
            .button(`§lPlot Management\n§rPrice = §a${discountedPrices[1]}`, "textures/items/pa_plot")
            .button(`§lShield\n§rPrice = §a${discountedPrices[2]}`, "textures/items/shield")
            .button(`§lNetherite Ingot\n§rPrice = §a${discountedPrices[3]}`, "textures/items/netherite_ingot")
            .button(`§l16 Torch\n§rPrice = §a${discountedPrices[4]}`, "textures/blocks/torch_on")
            .button(`§lElytra\n§rPrice = §a${discountedPrices[5]}`, "textures/items/elytra")
            .button(`§l6 Firework Rockets\n§rPrice = §a${discountedPrices[6]}`, "textures/items/firework_rocket")
            .button(`§lBundle\n§rPrice = §a${discountedPrices[7]}`, "textures/items/bundle")
            .button(`§lShulker Box\n§rPrice = §a${discountedPrices[8]}`, "textures/items/shulker_box")
            .button(`§l8 XP Bottles\n§rPrice = §a${discountedPrices[9]}`, "textures/items/experience_bottle")
            .button(`§lSpyglass\n§rPrice = §a${discountedPrices[10]}`, "textures/items/spyglass")
            .button(`§lFishing Rod\n§rPrice = §a${discountedPrices[11]}`, "textures/items/fishing_rod_uncast")
            .button('§l§cBack', "textures/ui/arrow_left");

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

            let selection = response.selection;
            if (selection === 12) return shopui(player); // Back button

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

            let itemPrice = discountedPrices[selection];
            let itemData = items[selection];

            let [item, quantity] = itemData.split(' ');
            quantity = parseInt(quantity, 10);

            const formattedName = item === "pa:plot" 
    ? "Plot Management" 
    : item.replace(/_/g, ' ').split(' ')
        .map(word => word.charAt(0).toUpperCase() + word.slice(1))
        .join(' ');
            const successMessage = quantity > 1 ? `${quantity} ${formattedName}s` : `${formattedName}`;

            if (updatedScore >= itemPrice) {
                player.runCommandAsync(`scoreboard players remove @s Money ${itemPrice}`);
                player.runCommandAsync(`give @s ${item} ${quantity}`);
                player.sendMessage(`§a${successMessage} Purchased Successfully!`);
                player.playSound("random.orb");

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

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


function armortrim(player) {
    const tags = player.getTags();
    const rankDiscounts = {
    	"gwim:God": { rank: "GOD", discount: 1.0 },
        "gwim:ElitePlus": { rank: "Elite+", discount: 1.0 },
        "gwim:Elite":     { rank: "Elite", discount: 0.8 },
        "gwim:VIPPlus":   { rank: "VIP+", discount: 0.6 },
        "gwim:VIP":       { rank: "VIP", discount: 0.4 }
    };

    let discount = 0;
    let rankName = "None";

    for (const tag in rankDiscounts) {
        if (tags.includes(tag)) {
            discount = rankDiscounts[tag].discount;
            rankName = rankDiscounts[tag].rank;
            break;
        }
    }

    let prices = Array(17).fill(2000);
    let items = [
        "netherite_upgrade_smithing_template 1",
        "wayfinder_armor_trim_smithing_template 1",
        "shaper_armor_trim_smithing_template 1",
        "host_armor_trim_smithing_template 1",
        "raiser_armor_trim_smithing_template 1",
        "silence_armor_trim_smithing_template 1",
        "sentry_armor_trim_smithing_template 1",
        "dune_armor_trim_smithing_template 1",
        "coast_armor_trim_smithing_template 1",
        "wild_armor_trim_smithing_template 1",
        "ward_armor_trim_smithing_template 1",
        "vex_armor_trim_smithing_template 1",
        "tide_armor_trim_smithing_template 1",
        "snout_armor_trim_smithing_template 1",
        "spire_armor_trim_smithing_template 1",
        "rib_armor_trim_smithing_template 1",
        "eye_armor_trim_smithing_template 1"
    ];

    let discountedPrices = prices.map(p => Math.floor(p * (1 - discount)));

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

        let form = new ActionFormData()
            .title('§lArmor Trims')
            .body(`Choose an Armor trim!\n§7Your Rank: §b§l${rankName}§r\n§7Discount: §a${Math.floor(discount * 100)}%\n§7Money: §a$${updatedScore}`)
            .button(`§lNetherite Upgrade\n§rPrice = §a${discountedPrices[0]}`, "textures/items/netherite_upgrade_smithing_template")
            .button(`§lWayfinder Armor Trim\n§rPrice = §a${discountedPrices[1]}`, "textures/items/wayfinder_armor_trim_smithing_template")
            .button(`§lShaper Armor Trim\n§rPrice = §a${discountedPrices[2]}`, "textures/items/shaper_armor_trim_smithing_template")
            .button(`§lHost Armor Trim\n§rPrice = §a${discountedPrices[3]}`, "textures/items/host_armor_trim_smithing_template")
            .button(`§lRaiser Armor Trim\n§rPrice = §a${discountedPrices[4]}`, "textures/items/raiser_armor_trim_smithing_template")
            .button(`§lSilence Armor Trim\n§rPrice = §a${discountedPrices[5]}`, "textures/items/silence_armor_trim_smithing_template")
            .button(`§lSentry Armor Trim\n§rPrice = §a${discountedPrices[6]}`, "textures/items/sentry_armor_trim_smithing_template")
            .button(`§lDune Armor Trim\n§rPrice = §a${discountedPrices[7]}`, "textures/items/dune_armor_trim_smithing_template")
            .button(`§lCoast Armor Trim\n§rPrice = §a${discountedPrices[8]}`, "textures/items/coast_armor_trim_smithing_template")
            .button(`§lWild Armor Trim\n§rPrice = §a${discountedPrices[9]}`, "textures/items/wild_armor_trim_smithing_template")
            .button(`§lWard Armor Trim\n§rPrice = §a${discountedPrices[10]}`, "textures/items/ward_armor_trim_smithing_template")
            .button(`§lVex Armor Trim\n§rPrice = §a${discountedPrices[11]}`, "textures/items/vex_armor_trim_smithing_template")
            .button(`§lTide Armor Trim\n§rPrice = §a${discountedPrices[12]}`, "textures/items/tide_armor_trim_smithing_template")
            .button(`§lSnout Armor Trim\n§rPrice = §a${discountedPrices[13]}`, "textures/items/snout_armor_trim_smithing_template")
            .button(`§lSpire Armor Trim\n§rPrice = §a${discountedPrices[14]}`, "textures/items/spire_armor_trim_smithing_template")
            .button(`§lRib Armor Trim\n§rPrice = §a${discountedPrices[15]}`, "textures/items/rib_armor_trim_smithing_template")
            .button(`§lEye Armor Trim\n§rPrice = §a${discountedPrices[16]}`, "textures/items/eye_armor_trim_smithing_template")
            .button('§l§cBack', "textures/ui/arrow_left");

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

            let selection = response.selection;
            if (selection === 17) return shopui(player); // Back button

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

            let itemPrice = discountedPrices[selection];
            let itemData = items[selection];

            let [item, quantity] = itemData.split(' ');
            quantity = parseInt(quantity, 10);

            let formattedName = item.replace(/_/g, ' ').replace(/\b\w/g, char => char.toUpperCase());
            let successMessage = `${formattedName}${quantity > 1 ? 's' : ''}`;

            if (updatedScore >= itemPrice) {
                player.runCommandAsync(`scoreboard players remove @s Money ${itemPrice}`);
                player.runCommandAsync(`give @s ${item} ${quantity}`);
                player.sendMessage(`§a${successMessage} Purchased Successfully!`);
                player.playSound("random.orb");

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

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