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

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

    showBlockMenu(player);
});

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

    showBlockMenu(damagingEntity);
});

function removeItems(player, typeId, amount) {
    const inventory = player.getComponent("minecraft:inventory").container;
    for (let slot = 0; slot < inventory.size; slot++) {
        const item = inventory.getItem(slot);
        if (!item || item.typeId !== typeId) continue;

        if (item.amount <= amount) {
            amount -= item.amount;
            inventory.setItem(slot, undefined);
        } else {
            const reducedItem = item.clone();
            reducedItem.amount = item.amount - amount;
            inventory.setItem(slot, reducedItem);
            amount = 0;
        }

        if (amount <= 0) break;
    }
}

function showBlockMenu(player) {
    const inventory = player.getComponent("minecraft:inventory").container;
    const moneyObjective = world.scoreboard.getObjective("Money");

    const BLOCKS = [
        { type: "minecraft:coal_block", name: "Coal Block", displayName: "§l§8Coal Block", price: 400 },
        { type: "minecraft:lapis_block", name: "Lapis Block", displayName: "§l§9Lapis Block", price: 150 },
        { type: "minecraft:iron_block", name: "Iron Block", displayName: "§l§fIron Block", price: 700 },
        { type: "minecraft:copper_block", name: "Copper Block", displayName: "§l§6Copper Block", price: 600 },
        { type: "minecraft:gold_block", name: "Gold Block", displayName: "§l§eGold Block", price: 800 },
        { type: "minecraft:diamond_block", name: "Diamond Block", displayName: "§l§bDiamond Block", price: 1000 },
        { type: "minecraft:emerald_block", name: "Emerald Block", displayName: "§l§aEmerald Block", price: 900 },
        { type: "minecraft:redstone_block", name: "Redstone Block", displayName: "§l§cRedstone Block", price: 300 },
        { type: "minecraft:quartz_block", name: "Quartz Block", displayName: "§l§fQuartz Block", price: 250 },
        { type: "minecraft:netherite_block", name: "Netherite Block", displayName: "§l§7Netherite Block", price: 8000 }
    ];

    const inventoryCounts = {};
    let totalSellable = 0;
    for (let slot = 0; slot < inventory.size; slot++) {
        const item = inventory.getItem(slot);
        if (!item) continue;
        inventoryCounts[item.typeId] = (inventoryCounts[item.typeId] || 0) + item.amount;
    }
    for (const block of BLOCKS) {
        totalSellable += inventoryCounts[block.type] ?? 0;
    }

    if (totalSellable === 0) {
        player.sendMessage("§cYou don't have any sellable blocks.");
        player.playSound("mob.villager.no");
        return;
    }

    player.playSound("random.pop2");
    player.playSound("mob.villager.haggle");

    const form = new ModalFormData()
        .title("§l[VIP] Mineral Merchant")
        .dropdown("§7Select a mode", [
            "§aManual Sell (Use sliders)",
            `§cSell All (${totalSellable})`
        ]);
        
    const priceInfo = BLOCKS.map(b => `§7- ${b.displayName} §f= §a$${b.price}`).join("\n");
    
    form.slider(
        `§l§6Welcome to [VIP] Mineral Merchant!\n§r§fUse the sliders below to sell specific amounts,\nor choose §c"Sell All"§f above to sell everything.\n\n§l§eSellable Blocks:\n${priceInfo}`,
        0, 0, 0, 0
    );

    for (const block of BLOCKS) {
        const count = inventoryCounts[block.type] ?? 0;
        form.slider(`${block.displayName} §7(0–${count})`, 0, count, 1, 0);
    }

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

        const selectedMode = res.formValues[0];
        const sliderValues = res.formValues.slice(2);

        if (selectedMode === 1) {
            // SELL ALL MODE
            let totalAmount = 0;
            let totalMoney = 0;
            let summaryLines = [];

            for (const block of BLOCKS) {
                const count = inventoryCounts[block.type] ?? 0;
                if (count > 0) {
                    const earn = count * block.price;
                    totalAmount += count;
                    totalMoney += earn;
                    summaryLines.push(`${block.displayName} §rx §e${count} §7= §a$${earn}§r`);
                }
            }

            const confirm = new MessageFormData()
                .title("§lConfirm Sell All")
                .body(`You're selling:\n\n${summaryLines.join("\n")}\n\n§l§fTotal: §a§l$${totalMoney}§r`)
                .button1("§cCancel")
                .button2("§aConfirm");

            confirm.show(player).then(confirmRes => {
                if (confirmRes.selection !== 1) {
                    player.sendMessage("§cSell cancelled.");
                    player.playSound("note.bass");
                    return;
                }

                for (const block of BLOCKS) {
                    const count = inventoryCounts[block.type] ?? 0;
                    if (count > 0) removeItems(player, block.type, count);
                }

                if (moneyObjective) {
                    const current = moneyObjective.getScore(player) ?? 0;
                    moneyObjective.setScore(player, current + totalMoney);
                }

                player.sendMessage(`§gYou sold ${totalAmount} blocks for §a$${totalMoney}`);
                player.playSound("random.orb");
            });

        } else {
            // MANUAL SLIDER MODE
            let totalAmount = 0;
            let totalMoney = 0;
            let summaryLines = [];

            for (let i = 0; i < sliderValues.length; i++) {
                const amount = sliderValues[i];
                const block = BLOCKS[i];
                if (amount > 0) {
                    const earn = amount * block.price;
                    totalAmount += amount;
                    totalMoney += earn;
                    summaryLines.push(`${block.displayName} §rx §e${amount} §7= §a$${earn}§r`);
                }
            }

            if (totalAmount === 0) {
                player.sendMessage("§cNothing selected to sell!");
                player.playSound("note.bass");
                return;
            }

            const confirm = new MessageFormData()
                .title("§lConfirm Sale")
                .body(`You're selling:\n\n${summaryLines.join("\n")}\n\n§l§fTotal: §a§l$${totalMoney}§r`)
                .button1("§cCancel")
                .button2("§aConfirm");

            confirm.show(player).then(confirmRes => {
                if (confirmRes.selection !== 1) {
                    player.sendMessage("§cSell cancelled.");
                    player.playSound("note.bass");
                    return;
                }

                for (let i = 0; i < sliderValues.length; i++) {
                    const amountToRemove = sliderValues[i];
                    if (amountToRemove > 0) {
                        removeItems(player, BLOCKS[i].type, amountToRemove);
                    }
                }

                if (moneyObjective) {
                    const current = moneyObjective.getScore(player) ?? 0;
                    moneyObjective.setScore(player, current + totalMoney);
                }

                player.sendMessage(`§gYou sold ${totalAmount} blocks for §a$${totalMoney}`);
                player.playSound("random.orb");
            });
        }
    });
}