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_custom3") return;

    showSellMenu(player);
});


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

    showSellMenu(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 {
            // ⚠️ Clone the item and set new amount properly
            const reducedItem = item.clone();
            reducedItem.amount = item.amount - amount;
            inventory.setItem(slot, reducedItem);
            amount = 0;
        }

        if (amount <= 0) break;
    }
}

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

    const items = [
        { type: "minecraft:cobblestone", name: "Cobblestone", displayName: "§lCobblestone", price: 6 },
        { type: "minecraft:flint", name: "Flint", displayName: "§lFlint", price: 40 },
        { type: "minecraft:coal", name: "Coal", displayName: "§lCoal", price: 10 },
        { type: "minecraft:iron_ingot", name: "Iron Ingot", displayName: "§l§fIron Ingot", price: 26 },
        { type: "minecraft:raw_iron", name: "Raw Iron", displayName: "§lRaw Iron", price: 12 },
        { type: "minecraft:gold_ingot", name: "Gold Ingot", displayName: "§l§eGold Ingot", price: 27 },
        { type: "minecraft:raw_gold", name: "Raw Gold", displayName: "§l§6Raw Gold", price: 13 },
        { type: "minecraft:lapis_lazuli", name: "Lapis Lazuli", displayName: "§l§9Lapis Lazuli", price: 2 },
        { type: "minecraft:redstone", name: "Redstone", displayName: "§l§cRedstone", price: 11 },
        { type: "minecraft:copper_ingot", name: "Copper Ingot", displayName: "§l§6Copper Ingot", price: 25 },
        { type: "minecraft:raw_copper", name: "Raw Copper", displayName: "§lRaw Copper", price: 11 },
        { type: "minecraft:emerald", name: "Emerald", displayName: "§l§aEmerald", price: 18 },
        { type: "minecraft:diamond", name: "Diamond", displayName: "§l§bDiamond", price: 19 },
        { type: "minecraft:quartz", name: "Quartz", displayName: "§l§fQuartz", price: 6 },
        { type: "minecraft:gold_nugget", name: "Gold Nugget", displayName: "§l§eGold Nugget", price: 3 },
        { type: "minecraft:netherite_scrap", name: "Netherite Scrap", displayName: "§l§8Netherite Scrap", price: 180 },
        { type: "minecraft:ancient_debris", name: "Ancient Debris", displayName: "§l§7Ancient Debris", price: 120 },
        { type: "minecraft:obsidian", name: "Obsidian", displayName: "§l§5Obsidian", price: 160 }
    ];

    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 item of items) {
        totalSellable += inventoryCounts[item.type] ?? 0;
    }

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

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

    const form = new ModalFormData()
        .title("§lThe Mineral Merchant")
        .dropdown("§7Select a mode", [
            "§aManual Sell (Use sliders)",
            `§cSell All (${totalSellable})`
        ])
        const priceInfo = items.map(i => `§7- ${i.displayName} §f= §a$${i.price}`).join("\n");
const currentMoney = moneyObjective?.getScore(player) ?? 0;

form.slider(
  `§l§6Welcome to the Mineral Merchant!\n§r§fYou have §a$${currentMoney}§f.\nUse the sliders below to sell specific amounts,\nor choose §c"Sell All"§f above to sell everything.\n\n§l§eSellable Items:\n${priceInfo}`,
  0, 0, 0, 0
);

    for (const item of items) {
        const count = inventoryCounts[item.type] ?? 0;
        form.slider(`${item.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 item of items) {
                const count = inventoryCounts[item.type] ?? 0;
                if (count > 0) {
                    const earn = count * item.price;
                    totalAmount += count;
                    totalMoney += earn;
                    summaryLines.push(`${item.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")      // Cancel as button 1 (index 0)
    .button2("§aConfirm");    // Confirm as button 2 (index 1)

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

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

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

                player.sendMessage(`§gYou sold ${totalAmount} items 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 item = items[i];
                if (amount > 0) {
                    const earn = amount * item.price;
                    totalAmount += amount;
                    totalMoney += earn;
                    summaryLines.push(`${item.displayName} §rx §e${amount} §7= §a$${earn}§r`);
                }
            }

            // ✅ If player selected nothing to sell
            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")    // Cancel is button 1 (index 0)
    .button2("§aConfirm");  // Confirm is button 2 (index 1)

confirm.show(player).then(confirmRes => {
    if (confirmRes.selection !== 1) {  // Confirm is index 1 now
        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, items[i].type, amountToRemove);
                    }
                }

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

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