import { system, world, Player, EquipmentSlot } from "@minecraft/server";

world.afterEvents.entityHitEntity.subscribe((event) => {
    const { hitEntity, damagingEntity } = event;

    if (damagingEntity instanceof Player) {
        const equipment = damagingEntity.getComponent("minecraft:equippable");

     
        if (equipment !== undefined) {
            const itemStack = equipment.getEquipment(EquipmentSlot.Mainhand);
            if (itemStack !== undefined && itemStack.typeId === "ww_dx:knife") {

              
                if (hitEntity.typeId === "ww_dx:cutting_board") {
  
                    processCuttingBoardInventory(hitEntity);

                }
            }
        }
    }
});


const recipes = [
    {
        output: "buns",
        ingredients: [
            { item: "minecraft:bread", count: 1 },
        ],
    },
    {
        output: "carrot_sticks",
        ingredients: [
            { item: "minecraft:carrot", count: 1 },
        ],
    },
    {
        output: "celery_sticks",
        ingredients: [
            { item: "ww_dx:celery", count: 1 },
        ],
    },
    {
        output: "chicken_sandwich",
        ingredients: [
            { item: "minecraft:bread", count: 1 },
            { item: "ww_dx:slice_of_chicken", count: 1 },
            { item: "ww_dx:lettuce", count: 1 },
            { item: "ww_dx:tomato", count: 1 },
        ],
    },
    {
        output: "chicken_slices",
        ingredients: [
            { item: "minecraft:cooked_chicken", count: 1 },
        ],
    },
    {
        output: "cod_sushi_roll",
        ingredients: [
            { item: "minecraft:cod", count: 1 },
            { item: "minecraft:kelp", count: 1 },
            { item: "ww_dx:rice", count: 1 },
        ],
    },
    {
        output: "fruit_kebab",
        ingredients: [
            { item: "ww_dx:star_fruit", count: 1 },
            { item: "ww_dx:banana", count: 1 },
            { item: "ww_dx:pineapple", count: 1 },
            { item: "minecraft:stick", count: 1 },
        ],
    },
    {
        output: "ham_sandwich",
        ingredients: [
            { item: "minecraft:bread", count: 1 },
            { item: "ww_dx:slice_of_ham", count: 1 },
            { item: "ww_dx:lettuce", count: 1 },
            { item: "ww_dx:tomato", count: 1 },
        ],
    },
    {
        output: "ham_slices",
        ingredients: [
            { item: "minecraft:cooked_porkchop", count: 1 },
        ],
    },
    {
        output: "raw_chicken_nuggets",
        ingredients: [
            { item: "minecraft:chicken", count: 6 },
        ],
    },
    {
        output: "salmon_sushi_roll",
        ingredients: [
            { item: "minecraft:salmon", count: 1 },
            { item: "minecraft:kelp", count: 1 },
            { item: "ww_dx:rice", count: 1 },
        ],
    },
    {
        output: "tropical_fish_sushi_roll",
        ingredients: [
            { item: "minecraft:tropical_fish", count: 1 },
            { item: "minecraft:kelp", count: 1 },
            { item: "ww_dx:rice", count: 1 },
        ],
    },
];

const cutting_board = new Map();


function processCuttingBoardInventory(entity) {
    const id = entity.id;

    if (cutting_board.get(id)?.isProcessing) {

        return;
    }

    const inventoryComponent = entity.getComponent("minecraft:inventory");

    if (!inventoryComponent || !inventoryComponent.container) {
        return;
    }

    const inventory = inventoryComponent.container;

    for (const recipe of recipes) {
        let matches = true;

        const ingredientsMap = new Map(
            recipe.ingredients.map((ingredient) => [ingredient.item, ingredient.count])
        );

        for (let i = 0; i < inventory.size; i++) {
            const item = inventory.getItem(i);
            if (item) {
                if (ingredientsMap.has(item.typeId)) {
                    const remainingCount = ingredientsMap.get(item.typeId) - item.amount;
                    if (remainingCount <= 0) {
                        ingredientsMap.delete(item.typeId);
                    } else {
                        ingredientsMap.set(item.typeId, remainingCount);
                    }
                } else {
                    matches = false;
                    break;
                }
            }
        }

        if (matches && ingredientsMap.size === 0) {
            entity.runCommandAsync("summon ww_dx:processing_particle ~ ~1 ~")
            for (const ingredient of recipe.ingredients) {
                let remainingToRemove = ingredient.count;

                for (let i = 0; i < inventory.size; i++) {
                    const item = inventory.getItem(i);
                    if (item && item.typeId === ingredient.item) {
                        if (item.amount > remainingToRemove) {
                            item.amount -= remainingToRemove;
                            inventory.setItem(i, item);
                            break;
                        } else {
                            remainingToRemove -= item.amount;
                            inventory.setItem(i, undefined);
                        }
                    }
                }
            }



            cutting_board.set(id, { isProcessing: true });
            system.runTimeout(() => {
                if (!entity.isValid()) return;
                const { x, y, z } = entity.location;

                entity.runCommandAsync(`loot spawn ${x} ${y + 1} ${z} loot ${recipe.output}`);
                entity.runCommandAsync("event entity @e[type=ww_dx:processing_particle,r=1] ww_dx:despawn")
                entity.runCommandAsync("playsound ww_dx:finish_cooking @a[r=5]")
                cutting_board.set(id, { isProcessing: false });
            }, 0);

            return;
        }
    }
}
