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

    showWoodSellMenu(player);
});


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

    showWoodSellMenu(damagingEntity);
});




function removeWood(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 showWoodSellMenu(player) {
    const inventory = player.getComponent("minecraft:inventory").container;
    const moneyObjective = world.scoreboard.getObjective("Money");

    const woodItems = [
    { type: "minecraft:oak_log", name: "Oak Log", displayName: "§6§lOak Log", price: 30 },       // Brownish
    { type: "minecraft:birch_log", name: "Birch Log", displayName: "§e§lBirch Log", price: 35 }, // Yellow
    { type: "minecraft:spruce_log", name: "Spruce Log", displayName: "§2§lSpruce Log", price: 38 }, // Dark Green
    { type: "minecraft:acacia_log", name: "Acacia Log", displayName: "§c§lAcacia Log", price: 40 }, // Red
    { type: "minecraft:dark_oak_log", name: "Dark Oak Log", displayName: "§8§lDark Oak Log", price: 42 }, // Dark Gray
    { type: "minecraft:jungle_log", name: "Jungle Log", displayName: "§a§lJungle Log", price: 45 }, // Light Green
    { type: "minecraft:cherry_log", name: "Cherry Log", displayName: "§d§lCherry Log", price: 48 }, // Pink
    { type: "minecraft:pale_oak_log", name: "Pale Oak Log", displayName: "§f§lPale Oak Log", price: 50 } // White
];

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

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

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

    const form = new ModalFormData()
        .title("§lThe Lumber Merchant")
        .dropdown("§7Select a mode", [
            "§aManual Sell (Use sliders)",
            `§cSell All (${totalSellable})`
        ]);

    const priceInfo = woodItems.map(i => `§7- ${i.displayName} §f= §a$${i.price}`).join("\n");
    const currentMoney = moneyObjective?.getScore(player) ?? 0;

    form.slider(
        `§l§6Welcome to the Lumber 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 Logs:\n${priceInfo}`,
        0, 0, 0, 0
    );

    for (const wood of woodItems) {
        const count = inventoryCounts[wood.type] ?? 0;
        form.slider(`${wood.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 wood of woodItems) {
                const count = inventoryCounts[wood.type] ?? 0;
                if (count > 0) {
                    const earn = count * wood.price;
                    totalAmount += count;
                    totalMoney += earn;
                    summaryLines.push(`${wood.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 wood of woodItems) {
                    const count = inventoryCounts[wood.type] ?? 0;
                    if (count > 0) removeWood(player, wood.type, count);
                }

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

                player.sendMessage(`§gYou sold ${totalAmount} logs 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 wood = woodItems[i];
                if (amount > 0) {
                    const earn = amount * wood.price;
                    totalAmount += amount;
                    totalMoney += earn;
                    summaryLines.push(`${wood.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) {
                        removeWood(player, woodItems[i].type, amountToRemove);
                    }
                }

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

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