import * as server from "@minecraft/server"


const skilletTimers = new Map()
const stoveTimers = new Map()
const stoveParticleIntervals = new Map()
const clearSkilletTimer = entityId => {
    const handle = skilletTimers.get(entityId)
    if (!handle) return
    server.system.clearRun(handle)
    skilletTimers.delete(entityId)
}
const clearStoveTimer = entityId => {
    const handle = stoveTimers.get(entityId)
    if (!handle) return
    server.system.clearRun(handle)
    stoveTimers.delete(entityId)
}
const clearStoveParticleInterval = entityId => {
    const handle = stoveParticleIntervals.get(entityId)
    if (!handle) return
    server.system.clearRun(handle)
    stoveParticleIntervals.delete(entityId)
}

server.system.beforeEvents.startup.subscribe(result => {
    result.blockComponentRegistry.registerCustomComponent("farmersdelight:safety_net", {
        onEntityFallOn: result => {
            //Good enough
            const rawVerticalStrength = result.fallDistance / 10;
            const verticalStrength = Math.max(Math.min(rawVerticalStrength, 1.4), 0);

            // console.warn("fallDistance: " + result.fallDistance)
            // console.warn("verticalStrength: " + verticalStrength)
            try {
                result.entity.applyKnockback({ x: 0, z: 0 }, verticalStrength);
            } catch { }
        },
        onTick: result => {
            let entity = result.block.dimension.getEntitiesAtBlockLocation({ x: result.block.center().x, y: result.block.center().y + 4, z: result.block.center().z });


            if (!entity || entity.length == 0) return;
            if (entity[0].getVelocity().y != 0) {
                // console.warn("entity velocity: " + entity[0]?.getVelocity().y)
            }

            entity.forEach(entity => {
                if (entity.isFalling && entity.getVelocity().y < -0.4) {
                    entity.addEffect("minecraft:resistance", 10, { showParticles: false, amplifier: 255 })
                }
            })
        }
    })
    result.blockComponentRegistry.registerCustomComponent("farmersdelight:rotation", {
        beforeOnPlayerPlace: result => {
            let direction = 0
            try {
                let rotationAngle = result.player.getRotation().y
                direction = rotationAngle >= -45 && rotationAngle < 45 ? 3 :
                    rotationAngle >= 45 && rotationAngle < 135 ? 4 :
                        rotationAngle >= -135 && rotationAngle < -45 ? 5 : 2;
            } catch (e) {
                //console.warn(e)
            }
            let state = result.block.permutation.getAllStates()
            state["block:rotation"] = direction
            result.permutationToPlace = server.BlockPermutation.resolve(result.permutationToPlace.type.id, state)
        }
    })
    result.blockComponentRegistry.registerCustomComponent("farmersdelight:skillet", {
        onTick: result => {
            let state = result.block.permutation.getAllStates()
            if (result.block.below(1).hasTag("stove_on")) state["block:stove_below"] = true
            else state["block:stove_below"] = false

            if (result.block.below(1).typeId == "minecraft:campfire" || result.block.below(1).typeId == "minecraft:soul_campfire") {
                state["block:is_campfire"] = true
                state["block:stove_below"] = true
            }

            const permutation = server.BlockPermutation.resolve(result.block.typeId, state)
            result.block.setPermutation(permutation)

            if (Math.random() < 0.08 && state["block:stove_below"] == true) {
                result.block.dimension.runCommand(`particle farmersdelight:pot_smoke ${result.block.location.x} ${result.block.location.y + 0.1} ${result.block.location.z}`)
            }
        },
        onPlayerInteract: result => {
            if (result.player.isSneaking || result.face != "Up") return;

            let item = result.player.getComponent("minecraft:equippable").getEquipment("Mainhand")
            const inventory = result.player.getComponent(server.EntityInventoryComponent.componentId).container;

            let entities = result.block.dimension.getEntitiesAtBlockLocation(result.block.center()).filter(entity => entity.typeId === "farmersdelight:skillet");

            let selectedColor;
            if (result.faceLocation.x > 0 && result.faceLocation.x < 0.5 && result.faceLocation.z > 0 && result.faceLocation.z < 0.5) {
                selectedColor = 1;
            } else if (result.faceLocation.x > 0 && result.faceLocation.x < 0.5 && result.faceLocation.z > 0.5 && result.faceLocation.z < 1) {
                selectedColor = 2;
            } else if (result.faceLocation.x > 0.5 && result.faceLocation.x < 1 && result.faceLocation.z > 0 && result.faceLocation.z < 0.5) {
                selectedColor = 3;
            } else if (result.faceLocation.x > 0.5 && result.faceLocation.x < 1 && result.faceLocation.z > 0.5 && result.faceLocation.z < 1) {
                selectedColor = 4;
            }

            let interactEntity = selectedColor ? entities.find(entity => entity.getComponent("minecraft:color").value == selectedColor) : null;

            if (!interactEntity) return;

            try {
                let enchantments = item.getComponent("minecraft:enchantable").getEnchantments().length
                if (enchantments > 0) {
                    result.player.onScreenDisplay.setActionBar({ "rawtext": [{ "translate": "farmersdelight:skillet_enchanted_item" }] })
                    return
                }
            } catch { }

            //Im not sure...
            // if (server.BlockTypes.get(item?.typeId)) {
            //     result.player.onScreenDisplay.setActionBar({ "rawtext": [{ "translate": "farmersdelight:block_not_cookable_actionbar" }] })
            //     return
            // }

            const existingTags = interactEntity.getTags();

            for (let tag of existingTags) {
                inventory.addItem(new server.ItemStack(tag, 1));
                clearSkilletTimer(interactEntity.id)
                clearStoveParticleInterval(interactEntity.id)
                interactEntity.removeTag(tag)
                interactEntity.runCommand(`replaceitem entity @s slot.weapon.mainhand 0 air`)
                return
            }
            if (!item) return;

            interactEntity.setRotation({ x: result.player.getRotation().x, y: result.player.getRotation().y - 160 })
            interactEntity.addTag(item.typeId)
            interactEntity.runCommand(`replaceitem entity @s slot.weapon.mainhand 0 ${item.typeId} 1`)

            if (interactEntity.getTags().length > 0) {
                /////////////Eliminar el Item del jugador/////////////
                if (item.amount == 1)
                    result.player.getComponent(server.EntityInventoryComponent.componentId).container.setItem(result.player.selectedSlotIndex, undefined)
                else {
                    item.amount--
                    result.player.getComponent(server.EntityInventoryComponent.componentId).container.setItem(result.player.selectedSlotIndex, item)
                }
            }

            if (result.block.below(1).hasTag("stove_on")) {
                interactEntity.runCommand(`event entity @s farmersdelight:cook_timer`)
                interactEntity.dimension.playSound("add_food", interactEntity.location)
                interactEntity.dimension.playSound("sizzle", interactEntity.location, { volume: 0.5 })
                const entityId = interactEntity.id
                clearSkilletTimer(entityId)
                clearStoveParticleInterval(entityId)

                const particleIntervalHandle = server.system.runInterval(() => {
                    try {
                        let interactEntity = selectedColor ? entities.find(entity => entity.getComponent("minecraft:color").value == selectedColor) : null;

                        if (!interactEntity) {
                            clearStoveParticleInterval(entityId)
                            return
                        }
                        interactEntity.dimension.spawnParticle("minecraft:basic_smoke_particle", interactEntity.location)
                    } catch { }
                }, 3)
                stoveParticleIntervals.set(entityId, particleIntervalHandle)

                const timeoutHandle = server.system.runTimeout(() => {
                    try {
                        let { x, y, z } = interactEntity.location
                        interactEntity?.runCommand("function cook_farmersdelight")
                        interactEntity?.runCommand("function cook_crabbersdelight")
                        interactEntity?.runCommand("function cook_sunflowerdelight")
                        interactEntity?.runCommand("function cook_endsdelight")
                        interactEntity?.runCommand("function cook_spanishdelight")
                        interactEntity?.triggerEvent("farmersdelight:despawn")

                        result.block.dimension.spawnEntity("farmersdelight:skillet", { x: x, y: y, z: z }).triggerEvent("farmersdelight:skillet_" + selectedColor)
                    } catch { }
                    skilletTimers.delete(entityId)
                    server.system.runTimeout(() => {
                        clearStoveParticleInterval(entityId)
                        result.player.runCommand(`execute positioned ${result.block.center().x} ${result.block.center().y} ${result.block.center().z} run tp @e[type=item,r=1.1] ${result.block.center().x} ${result.block.center().y} ${result.block.center().z}`)
                    }, 1)
                }, 100)
                skilletTimers.set(entityId, timeoutHandle)
            }
        }
    })
    result.blockComponentRegistry.registerCustomComponent("farmersdelight:stove", {
        onPlayerInteract: result => {

            let itemStove = result.player.getComponent("minecraft:equippable").getEquipment("Mainhand")

            if (result.face == "Up" && !result.player.isSneaking) {
                if (itemStove?.typeId == "farmersdelight:cooking_pot") {
                    result.player.onScreenDisplay.setActionBar({ "rawtext": [{ "translate": "farmersdelight:cooking_pot_actionbar" }] })
                    return
                }
                if (itemStove?.typeId == "farmersdelight:skillet") {
                    result.player.onScreenDisplay.setActionBar({ "rawtext": [{ "translate": "farmersdelight:skillet_actionbar" }] })
                    return
                }

                // if (server.BlockTypes.get(itemStove.typeId)) {
                //     result.player.onScreenDisplay.setActionBar({ "rawtext": [{ "translate": "farmersdelight:block_not_cookable_actionbar" }] })
                //     return
                // } else if (result.block.above().typeId == "farmersdelight:skillet") return;

                let item = result.player.getComponent("minecraft:equippable").getEquipment("Mainhand")
                const inventory = result.player.getComponent(server.EntityInventoryComponent.componentId).container;

                let entities = result.block.dimension.getEntitiesAtBlockLocation(result.block.center()).filter(entity => entity.typeId === "farmersdelight:stove");

                //console.warn(entities.length)

                // Taking block rotation into account was more difficult than I thought
                let rotation = result.block.permutation.getState("block:rotation"); // 2, 3, 4, 5

                let selectedColor;

                let clickedX = result.faceLocation.x - 0.5;
                let clickedZ = result.faceLocation.z - 0.5;

                let localX, localZ;
                switch (rotation) {
                    case 2:
                        localX = clickedZ;
                        localZ = -clickedX;
                        break;
                    case 3:
                        localX = -clickedZ;
                        localZ = clickedX;
                        break;
                    case 4:
                        localX = clickedX;
                        localZ = clickedZ;
                        break;
                    case 5:
                        localX = -clickedX;
                        localZ = -clickedZ;
                        break;
                    default:
                        localX = clickedX;
                        localZ = clickedZ;
                }

                let normalizedX = localX + 0.5;
                let normalizedZ = localZ + 0.5;

                if (normalizedX >= 0 && normalizedX < 1 && normalizedZ >= 0 && normalizedZ < 1) {
                    let col = Math.floor(normalizedX * 2); // 0,1
                    let row = Math.floor(normalizedZ * 3); // 0,1,2
                    selectedColor = row * 2 + col + 1;
                }

                let interactEntity = selectedColor ? entities.find(entity => entity.getComponent("minecraft:color").value == selectedColor) : null;
                // console.warn(selectedColor)

                if (!interactEntity) return;

                try {
                    let enchantments = item.getComponent("minecraft:enchantable").getEnchantments().length
                    if (enchantments > 0) {
                        result.player.onScreenDisplay.setActionBar({ "rawtext": [{ "translate": "farmersdelight:skillet_enchanted_item" }] })
                        return
                    }
                } catch { }

                const existingTags = interactEntity.getTags();

                for (let tag of existingTags) {
                    inventory.addItem(new server.ItemStack(tag, 1));
                    clearStoveTimer(interactEntity.id)
                    clearStoveParticleInterval(interactEntity.id)
                    interactEntity.removeTag(tag)
                    interactEntity.runCommand(`replaceitem entity @s slot.weapon.mainhand 0 air`)
                    return
                }
                if (!item) return;

                interactEntity.setRotation({ x: result.player.getRotation().x, y: result.player.getRotation().y - 160 })
                interactEntity.addTag(item.typeId)
                interactEntity.runCommand(`replaceitem entity @s slot.weapon.mainhand 0 ${item.typeId} 1`)

                if (interactEntity.getTags().length > 0) {
                    /////////////Eliminar el Item del jugador/////////////
                    if (item.amount == 1)
                        result.player.getComponent(server.EntityInventoryComponent.componentId).container.setItem(result.player.selectedSlotIndex, undefined)
                    else {
                        item.amount--
                        result.player.getComponent(server.EntityInventoryComponent.componentId).container.setItem(result.player.selectedSlotIndex, item)
                    }
                }

                if (result.block.hasTag("stove_on")) {
                    interactEntity.runCommand(`event entity @s farmersdelight:cook_timer`)
                    interactEntity.dimension.playSound("add_food", interactEntity.location)
                    interactEntity.dimension.playSound("sizzle", interactEntity.location, { volume: 0.5 })
                    const entityId = interactEntity.id
                    clearStoveTimer(entityId)
                    clearStoveParticleInterval(entityId)

                    const particleIntervalHandle = server.system.runInterval(() => {
                        try {
                            let interactEntity = selectedColor ? entities.find(entity => entity.getComponent("minecraft:color").value == selectedColor) : null;

                            if (!interactEntity) {
                                clearStoveParticleInterval(entityId)
                                return
                            }
                            interactEntity.dimension.spawnParticle("minecraft:basic_smoke_particle", interactEntity.location)
                        } catch { }
                    }, 3)
                    stoveParticleIntervals.set(entityId, particleIntervalHandle)

                    const timeoutHandle = server.system.runTimeout(() => {
                        try {
                            let { x, y, z } = interactEntity.location
                            interactEntity?.runCommand("function cook_farmersdelight")
                            interactEntity?.runCommand("function cook_crabbersdelight")
                            interactEntity?.runCommand("function cook_sunflowerdelight")
                            interactEntity?.runCommand("function cook_endsdelight")
                            interactEntity?.runCommand("function cook_spanishdelight")
                            interactEntity?.triggerEvent("farmersdelight:despawn")

                            result.block.dimension.spawnEntity("farmersdelight:stove", { x: x, y: y, z: z }).triggerEvent("farmersdelight:stove_" + selectedColor)
                        } catch { }
                        stoveTimers.delete(entityId)
                        clearStoveParticleInterval(entityId)
                        server.system.runTimeout(() => {
                            result.player.runCommand(`execute positioned ${result.block.center().x} ${result.block.center().y} ${result.block.center().z} run tp @e[type=item,r=1.1] ${result.block.center().x} ${result.block.center().y + 0.5} ${result.block.center().z}`)
                        }, 1)
                    }, 600)
                    stoveTimers.set(entityId, timeoutHandle)
                }
            }

            if (!itemStove) return;

            let state = result.block.permutation.getAllStates()
            let item = result.player.getComponent("minecraft:equippable").getEquipment("Mainhand")
            if (state["block:lit"] == true && item?.typeId == "minecraft:water_bucket") {
                state["block:lit"] = false
                result.player.getComponent("minecraft:equippable").setEquipment("Mainhand", new server.ItemStack("minecraft:bucket", 1))
                result.player.dimension.playSound("extinguish.candle", result.block.location)
            }
            else if (state["block:lit"] == false && item?.typeId == "minecraft:flint_and_steel") {
                state["block:lit"] = true
                if (item.getComponent("minecraft:durability").damage < item.getComponent("minecraft:durability").maxDurability) {
                    item.getComponent("minecraft:durability").damage++
                    result.player.getComponent("minecraft:equippable").setEquipment("Mainhand", item)
                }
                else {
                    result.player.getComponent("minecraft:equippable").setEquipment("Mainhand", undefined)
                    result.player.dimension.playSound("random.break", result.player.location)
                }
                result.player.dimension.playSound("fire.ignite", result.block.location)
            }
            result.block.setPermutation(server.BlockPermutation.resolve(result.block.typeId, state))
        }
    })
    result.blockComponentRegistry.registerCustomComponent("farmersdelight:cutting_board", {
        onPlayerInteract: result => {

            if (result.player.isSneaking || result.face != "Up") return;

            let isBlock = isBlockFunction(result.itemStack)

            //console.warn(isBlock)

            function isBlockFunction(itemStack) {
                if (!itemStack) return undefined;
                return !!server.BlockTypes.get(itemStack.typeId);
            }

            let item = result.player.getComponent("minecraft:equippable").getEquipment("Mainhand")
            let entity = result.block.dimension.getEntitiesAtBlockLocation(result.block.center()).filter(e => e.typeId === 'farmersdelight:cutting_board_entity');

            //Hand
            if (!result.player.getComponent("minecraft:equippable").getEquipment("Mainhand")) {
                if (entity[0].getTags().length > 0) {
                    entity[0].getTags().forEach(tag => {
                        /////////////Devolver el item ya colocado/////////////
                        result.player.getComponent(server.EntityInventoryComponent.componentId).container.addItem(new server.ItemStack(tag, 1))
                        entity[0].runCommand(`replaceitem entity @s slot.weapon.mainhand 0 air`)
                        entity[0].removeTag(tag)
                    })
                }
            }
            else {
                let tags = item.getTags()

                if (tags.includes('fd_knife')) {
                    result.player.playSound("knife_cuts", result.player.location)
                    let knife_functions = [
                        "function knife_farmersdelight",
                        "function knife_crabbersdelight",
                        "function knife_sunflowerdelight",
                        "function knife_nethersdelight",
                        "function knife_brewinandchewin",
                        "function knife_largemeals",
                        "function knife_endsdelight",
                        "function knife_spanishdelight"]

                    for (let functions of knife_functions) {
                        entity[0].runCommand(`${functions}`)
                    }
                    entity[0].runCommand(`event entity @s farmersdelight:respawn`)
                }
                else if (tags.includes('minecraft:is_axe')) {
                    let axe_functions = [
                        "function axe_farmersdelight",
                        "function axe_crabbersdelight",
                        "function axe_sunflowerdelight",
                        "function axe_nethersdelight",
                        "function axe_brewinandchewin",
                        "function axe_largemeals"]

                    for (let functions of axe_functions) {
                        entity[0].runCommand(`${functions}`)
                    }
                    entity[0].runCommand(`event entity @s farmersdelight:respawn`)
                }
                else if (item.typeId == "minecraft:shears") {
                    let shears_functions = [
                        "function shears_farmersdelight",
                        "function shears_crabbersdelight",
                        "function shears_sunflowerdelight",
                        "function shears_nethersdelight",
                        "function shears_brewinandchewin",
                        "function shears_largemeals"]

                    for (let functions of shears_functions) {
                        entity[0].runCommand(`${functions}`)
                    }
                    entity[0].runCommand(`event entity @s farmersdelight:respawn`)
                }
                else if (tags.includes('minecraft:is_pickaxe')) {
                    let pickaxe_functions = [
                        "function pickaxe_farmersdelight",
                        "function pickaxe_crabbersdelight",
                        "function pickaxe_sunflowerdelight",
                        "function pickaxe_nethersdelight",
                        "function pickaxe_brewinandchewin",
                        "function pickaxe_largemeals"]

                    for (let functions of pickaxe_functions) {
                        entity[0].runCommand(`${functions}`)
                    }
                    entity[0].runCommand(`event entity @s farmersdelight:respawn`)
                }
                else if (tags.includes('minecraft:is_shovel')) {
                    let shovel_functions = [
                        "function shovel_farmersdelight",
                        "function shovel_crabbersdelight",
                        "function shovel_sunflowerdelight",
                        "function shovel_nethersdelight",
                        "function shovel_brewinandchewin",
                        "function shovel_largemeals"]

                    for (let functions of shovel_functions) {
                        entity[0].runCommand(`${functions}`)
                    }
                    entity[0].runCommand(`event entity @s farmersdelight:respawn`)
                }
                else {
                    let stop = false


                    try {
                        let enchantments = item.getComponent("minecraft:enchantable").getEnchantments().length
                        if (enchantments > 0) {
                            result.player.onScreenDisplay.setActionBar({ "rawtext": [{ "translate": "farmersdelight:cutting_board_enchanted_item" }] })
                            result.player.playSound("step.wood", result.block.center())
                            return
                        }
                    } catch { }

                    /////////////Entidad toma el item/////////////
                    entity[0].getTags().forEach(tag => {
                        /////////////Devolver el item ya colocado/////////////
                        if (item.typeId == tag) {
                            ///////////Si el item el mano es igual al de la tabla de cortar/////////////
                            result.player.getComponent(server.EntityInventoryComponent.componentId).container.addItem(new server.ItemStack(item.typeId, 1))
                            entity[0].runCommand(`replaceitem entity @s slot.weapon.mainhand 0 air`)
                            stop = true
                        }
                        else {
                            result.player.getComponent(server.EntityInventoryComponent.componentId).container.addItem(new server.ItemStack(tag, 1))

                        }

                        entity[0].removeTag(tag)

                    })

                    if (stop) return;

                    entity[0].addTag(item.typeId)

                    entity[0].runCommand(`replaceitem entity @s slot.weapon.mainhand 0 ${item.typeId} 1`)
                    entity[0].dimension.playSound("step.wood", entity[0].location)
                    //////////////////////////////////////////////

                    if (entity[0].getTags().length > 0) {
                        /////////////Eliminar el Item del jugador/////////////
                        if (item.amount == 1)
                            result.player.getComponent(server.EntityInventoryComponent.componentId).container.setItem(result.player.selectedSlotIndex, undefined)
                        else {
                            item.amount--
                            result.player.getComponent(server.EntityInventoryComponent.componentId).container.setItem(result.player.selectedSlotIndex, item)
                        }
                    }
                }
            }
        }
    })
    result.blockComponentRegistry.registerCustomComponent("farmersdelight:cooking_pot", {
        onTick: result => {
            let state = result.block.permutation.getAllStates()
            if (result.block.below(1).hasTag("stove_on") || result.block.below(1).typeId == "minecraft:campfire" || result.block.below(1).typeId == "minecraft:soul_campfire") {
                state["block:stove_below"] = true


                if (result.block.below(1).typeId == "minecraft:campfire" || result.block.below(1).typeId == "minecraft:soul_campfire") {
                    state["block:is_campfire"] = true
                }
            }
            else state["block:stove_below"] = false

            if (state["block:stove_below"] == true) {
                if (Math.random() < 0.06) {
                    result.block.dimension.spawnParticle("farmersdelight:pot_bubble", { x: result.block.center().x, y: result.block.center().y + 0.20, z: result.block.center().z })
                }
                if (Math.random() < 0.03) {
                    result.block.dimension.spawnParticle("farmersdelight:pot_smoke", { x: result.block.center().x, y: result.block.center().y + 0.25, z: result.block.center().z })
                }
            }
            result.block.setPermutation(server.BlockPermutation.resolve(result.block.typeId, state))
        }
    })
    result.blockComponentRegistry.registerCustomComponent("farmersdelight:mushroom_grow", {
        onRandomTick: result => {
            if (Math.random() < 0.4) {
                let state = result.block.permutation.getAllStates()
                state["farmersdelight:age"] = Math.min(state["farmersdelight:age"] + 1, 4)
                result.block.setPermutation(server.BlockPermutation.resolve(result.block.typeId, state))
            }
        }
    })
    result.blockComponentRegistry.registerCustomComponent('farmersdelight:block_inventory', {
        onPlayerInteract: result => {
            let state = result.block.permutation.getAllStates()
            state["block:inventory"] = true

            result.dimension.playSound("block.barrel.open", result.block.center())

            const permutation = server.BlockPermutation.resolve(result.block.typeId, state)
            result.block.setPermutation(permutation)

        }
    })
    result.blockComponentRegistry.registerCustomComponent('farmersdelight:inventory_tick', {
        onTick: result => {
            let state = result.block.permutation.getAllStates()
            state["block:inventory"] = false

            result.dimension.playSound("block.barrel.close", result.block.center())

            const permutation = server.BlockPermutation.resolve(result.block.typeId, state)
            result.block.setPermutation(permutation)
        }
    })
    result.blockComponentRegistry.registerCustomComponent("farmersdelight:compost", {
        onRandomTick: result => {
            result.block.dimension.spawnParticle("farmersdelight:organic_compost", result.block.center())
            let state = result.block.permutation.getAllStates()
            state["block:compost"]++
            result.block.setPermutation(server.BlockPermutation.resolve(result.block.typeId, state))
            if (state["block:compost"] == 4) result.block.setType("farmersdelight:rich_soil")
        }
    })
    result.blockComponentRegistry.registerCustomComponent("farmersdelight:rich_soil", {
        onPlayerInteract: result => {
            let item = result.player.getComponent("equippable").getEquipment("Mainhand")
            if (!item) return
            if (item.typeId == "minecraft:wooden_hoe" ||
                item.typeId == "minecraft:stone_hoe" ||
                item.typeId == "minecraft:iron_hoe" ||
                item.typeId == "minecraft:golden_hoe" ||
                item.typeId == "minecraft:diamond_hoe" ||
                item.typeId == "minecraft:netherite_hoe") {

                result.block.dimension.playSound("use.gravel", result.block.location)
                result.block.setType("farmersdelight:rich_soil_farmland")
                if (item.getComponent("minecraft:durability").damage < item.getComponent("minecraft:durability").maxDurability) {
                    item.getComponent("minecraft:durability").damage++
                    result.player.getComponent("minecraft:equippable").setEquipment("Mainhand", item)
                }
                else {
                    result.player.getComponent("minecraft:equippable").setEquipment("Mainhand", undefined)
                    result.player.dimension.playSound("random.break", result.player.location)
                }
            }
            else if (result.face == "Up" && item.typeId == "minecraft:red_mushroom" && !result.block.above(1).hasTag("mushroom_colony")) {
                if (item.amount == 1)
                    result.player.getComponent("minecraft:equippable").setEquipment("Mainhand", undefined)
                else {
                    item.amount--
                    result.player.getComponent("minecraft:equippable").setEquipment("Mainhand", item)
                }
                result.block.above(1).setType("farmersdelight:red_mushroom_colony")
                result.block.dimension.playSound("dig.grass", result.block.location)
            }
            else if (result.face == "Up" && item.typeId == "minecraft:brown_mushroom" && !result.block.above(1).hasTag("mushroom_colony")) {
                if (item.amount == 1)
                    result.player.getComponent("minecraft:equippable").setEquipment("Mainhand", undefined)
                else {
                    item.amount--
                    result.player.getComponent("minecraft:equippable").setEquipment("Mainhand", item)
                }
                result.block.above(1).setType("farmersdelight:brown_mushroom_colony")
                result.block.dimension.playSound("dig.grass", result.block.location)
            }
        }
    })
    result.blockComponentRegistry.registerCustomComponent("farmersdelight:farmland", {
        onRandomTick: result => {
            let state = result.block.permutation.getAllStates()
            function hasWaterNearby(block) {
                for (let dx = -4; dx <= 4; dx++) {
                    for (let dz = -4; dz <= 4; dz++) {
                        // Saltar el bloque central (0, 0) si es necesario
                        if (dx === 0 && dz === 0) continue;

                        // Obtener el bloque vecino
                        let neighborBlock = block.dimension.getBlock({
                            x: block.location.x + dx,
                            y: block.location.y,
                            z: block.location.z + dz
                        });

                        if (!neighborBlock) continue;

                        // Verificar si el bloque vecino tiene el tag 'water' o si esta waterlogged
                        if (neighborBlock.getTags().includes('water') || neighborBlock.isWaterlogged) {
                            return true;
                        }
                    }
                }
                return false;
            }
            state["wiki:wet_farmland"] = hasWaterNearby(result.block)

            result.block.setPermutation(server.BlockPermutation.resolve(result.block.typeId, state))
            // if (state["wiki:wet_farmland"] == false && Math.random() < 0.8 && result.block.typeId == "farmersdelight:delight_farmland") { result.block.setType("farmersdelight:delight_dirt"); return }
        }
        // onEntityFallOn: result => {
        //     if (result.fallDistance > 1.10 && Math.random() < 0.6 && result.entity.typeId != "minecraft:item" && result.block.typeId == "farmersdelight:delight_farmland") {
        //         result.block.setType("farmersdelight:delight_dirt")
        //     }
        // }
    })
    result.blockComponentRegistry.registerCustomComponent("farmersdelight:pie", {
        onPlayerInteract: result => {
            let state = result.block.permutation.getAllStates()
            state["block:slice"]--
            result.block.dimension.playSound("random.eat", result.player.location)
            result.player.addEffect("saturation", 1, { amplifier: 3, showParticles: false })
            result.player.addEffect("speed", server.TicksPerSecond * 30, { amplifier: 0, showParticles: false })
            result.block.setPermutation(server.BlockPermutation.resolve(result.block.typeId, state))

            if (state["block:slice"] == 0) result.block.setType("minecraft:air")
        }
    })
    //Feast Food
    result.blockComponentRegistry.registerCustomComponent("farmersdelight:stuffed_pumpkin_block", {
        onPlayerInteract: result => {
            let item = result.player.getComponent("equippable").getEquipment("Mainhand")
            let state = result.block.permutation.getAllStates()


            if (item?.typeId == "minecraft:bowl") {
                if (item.amount == 1)
                    result.player.getComponent("minecraft:equippable").setEquipment("Mainhand", undefined)
                else {
                    item.amount--
                    result.player.getComponent("minecraft:equippable").setEquipment("Mainhand", item)
                }
                result.block.dimension.playSound("armor.equip_generic", result.player.location)

                result.player.getComponent("inventory").container.addItem(new server.ItemStack("farmersdelight:stuffed_pumpkin", 1))
                state["block:stage"]++
                result.block.setPermutation(server.BlockPermutation.resolve(result.block.typeId, state))
                if (state["block:stage"] == 4) result.block.setType("minecraft:air")
            }
            else {
                result.player.onScreenDisplay.setActionBar({ "rawtext": [{ "translate": "need.bowl.deny" }] })
            }
        }
    })
    result.blockComponentRegistry.registerCustomComponent("farmersdelight:shepherds_pie_block", {
        onPlayerInteract: result => {
            let item = result.player.getComponent("equippable").getEquipment("Mainhand")
            let state = result.block.permutation.getAllStates()

            if (state["block:stage"] == 4) {
                result.block.dimension.runCommand(`loot spawn ${result.block.center().x} ${result.block.center().y} ${result.block.center().z} loot "rice_roll_medley"`)
                result.block.setType("minecraft:air")
                result.block.dimension.playSound("use.cloth", result.block.location)
                return
            }

            if (item?.typeId == "minecraft:bowl") {
                if (item.amount == 1)
                    result.player.getComponent("minecraft:equippable").setEquipment("Mainhand", undefined)
                else {
                    item.amount--
                    result.player.getComponent("minecraft:equippable").setEquipment("Mainhand", item)
                }

                result.block.dimension.playSound("armor.equip_generic", result.player.location)
                result.player.getComponent("inventory").container.addItem(new server.ItemStack("farmersdelight:shepherds_pie", 1))
                state["block:stage"]++
                result.block.setPermutation(server.BlockPermutation.resolve(result.block.typeId, state))
            }
            else {
                result.player.onScreenDisplay.setActionBar({ "rawtext": [{ "translate": "need.bowl.deny" }] })
            }
        }
    })
    result.blockComponentRegistry.registerCustomComponent("farmersdelight:roast_chicken_block", {
        onPlayerInteract: result => {
            let item = result.player.getComponent("equippable").getEquipment("Mainhand")
            let state = result.block.permutation.getAllStates()

            if (state["block:stage"] == 4) {
                result.block.dimension.runCommand(`loot spawn ${result.block.center().x} ${result.block.center().y} ${result.block.center().z} loot "roast_chicken"`)
                result.block.setType("minecraft:air")
                result.block.dimension.playSound("use.cloth", result.block.location)
                return
            }

            if (item?.typeId == "minecraft:bowl") {
                if (item.amount == 1)
                    result.player.getComponent("minecraft:equippable").setEquipment("Mainhand", undefined)
                else {
                    item.amount--
                    result.player.getComponent("minecraft:equippable").setEquipment("Mainhand", item)
                }

                result.block.dimension.playSound("armor.equip_generic", result.player.location)
                result.player.getComponent("inventory").container.addItem(new server.ItemStack("farmersdelight:roast_chicken", 1))
                state["block:stage"]++
                result.block.setPermutation(server.BlockPermutation.resolve(result.block.typeId, state))
            }
            else {
                result.player.onScreenDisplay.setActionBar({ "rawtext": [{ "translate": "need.bowl.deny" }] })
            }
        }
    })
    result.blockComponentRegistry.registerCustomComponent("farmersdelight:rice_roll_medley_block", {
        onPlayerInteract: result => {
            let state = result.block.permutation.getAllStates()
            //query.block_state('block:slice')==6||query.block_state('block:slice')==7||query.block_state('block:slice')==8
            if (state["block:slice"] == 6 || state["block:slice"] == 7 || state["block:slice"] == 8) {
                result.block.dimension.runCommand(`loot spawn ${result.block.center().x} ${result.block.center().y} ${result.block.center().z} loot "kelp_roll_slice"`)
                result.block.dimension.playSound("armor.equip_generic", result.block.location)
            }
            if (state["block:slice"] == 3 || state["block:slice"] == 4 || state["block:slice"] == 5) {
                result.block.dimension.runCommand(`loot spawn ${result.block.center().x} ${result.block.center().y} ${result.block.center().z} loot "salmon_roll"`)
                result.block.dimension.playSound("armor.equip_generic", result.block.location)
            }
            if (state["block:slice"] == 1 || state["block:slice"] == 2) {
                result.block.dimension.runCommand(`loot spawn ${result.block.center().x} ${result.block.center().y} ${result.block.center().z} loot "cod_roll"`)
                result.block.dimension.playSound("armor.equip_generic", result.block.location)
            }
            if (state["block:slice"] == 0) {
                result.block.dimension.runCommand(`loot spawn ${result.block.center().x} ${result.block.center().y} ${result.block.center().z} loot "rice_roll_medley"`)
                result.block.dimension.playSound("use.cloth", result.block.location)
                result.block.setType("minecraft:air")
                return
            }
            state["block:slice"]--
            result.block.setPermutation(server.BlockPermutation.resolve(result.block.typeId, state))
        }
    })
    result.blockComponentRegistry.registerCustomComponent("farmersdelight:honey_glazed_ham_block", {
        onPlayerInteract: result => {
            let item = result.player.getComponent("equippable").getEquipment("Mainhand")
            let state = result.block.permutation.getAllStates()

            if (state["block:stage"] == 4) {
                result.block.dimension.runCommand(`loot spawn ${result.block.center().x} ${result.block.center().y} ${result.block.center().z} loot "roast_chicken"`)
                result.block.setType("minecraft:air")
                result.block.dimension.playSound("use.cloth", result.block.location)
                return
            }

            if (item?.typeId == "minecraft:bowl") {
                if (item.amount == 1)
                    result.player.getComponent("minecraft:equippable").setEquipment("Mainhand", undefined)
                else {
                    item.amount--
                    result.player.getComponent("minecraft:equippable").setEquipment("Mainhand", item)
                }

                result.block.dimension.playSound("armor.equip_generic", result.player.location)
                result.player.getComponent("inventory").container.addItem(new server.ItemStack("farmersdelight:honey_glazed_ham", 1))
                state["block:stage"]++
                result.block.setPermutation(server.BlockPermutation.resolve(result.block.typeId, state))
            }
            else {
                result.player.onScreenDisplay.setActionBar({ "rawtext": [{ "translate": "need.bowl.deny" }] })
            }
        }
    })
})