import { world, ItemStack, GameMode, system } from "@minecraft/server";
import { updateBlock } from "../utils/block";
import { consumeEquipped } from "../utils/item";

const Utils = {
    getPlayerEquipment(player) {
        try {
            return player.getComponent("equippable");
        } catch (e) {
            return null;
        }
    },
    getSelectedItem(player) {
        const equip = this.getPlayerEquipment(player);
        try {
            return equip ? equip.getEquipment("Mainhand") : null;
        } catch (e) {
            return null;
        }
    },
    consumeItem(player, item) {
        try {
            if (player.getGameMode && player.getGameMode() === GameMode.creative) return;
        } catch (e) {}
        const equip = this.getPlayerEquipment(player);
        if (equip) consumeEquipped(equip, item);
    },
    setBlockState(block, stateName, value) {
        try {
            const newPerm = block.permutation.withState(stateName, value);
            block.setPermutation(newPerm);
        } catch (err) {
            try { updateBlock(block, { [stateName]: value }); } catch (e) {}
        }
    },
    giveItem(player, id) {
        try {
            let stack;
            try { stack = new ItemStack(id); } catch (e) {
                try { stack = ItemStack.create(id); } catch (e2) { stack = null; }
            }
            if (stack) player.getComponent("inventory").container.addItem(stack);
        } catch (e) {}
    },
    playSound(block, sound) {
        try { block.dimension.playSound(sound, block.location); } catch (e) {}
    },
    spawnParticle(block, particle) {
        const loc = block.location;
        try {
            block.dimension.spawnParticle(particle, {
                x: loc.x + 0.5,
                y: loc.y + 1,
                z: loc.z + 0.5
            });
        } catch (e) {}
    }
};

function scheduleDone(block) {
    try {
        const ticks = 20 + Math.floor(Math.random() * 1);
        const delayMs = ticks * 10;
        system.runTimeout(() => {
            try {
                const b = block.dimension.getBlock(block.location);
                if (!b) return;
                const mode = b.permutation.getState("peach:mode");
                if (mode === "1") {
                    Utils.setBlockState(b, "peach:mode", "2");
                    Utils.spawnParticle(b, "minecraft:campfire_smoke_particle");
                }
            } catch (err) {}
        }, delayMs);
    } catch (e) {}
}

world.beforeEvents.worldInitialize.subscribe(init => {
    init.blockComponentRegistry.registerCustomComponent("peach:frying_pan_logic", {
        onPlayerInteract: e => {
            const { player, block } = e;
            if (!player || !block) return;

            const item = Utils.getSelectedItem(player);
            const recipe = block.permutation.getState("peach:recipe");
            const mode = block.permutation.getState("peach:mode");

            if (item && item.typeId.startsWith("zz:cancel_block")) {
                e.cancel = true;
            }

            // ---------------- Put ----------------
            if (recipe === "0" && mode === "0") {
                if (item.typeId === "minecraft:egg" || item.typeId === "minecraft:blue_egg" || item.typeId === "minecraft:brown_egg" || item.typeId === "minecraft:turtle_egg" || item.typeId === "minecraft:sniffer_egg") {
                    Utils.setBlockState(block, "peach:mode", "1");
                    Utils.setBlockState(block, "peach:recipe", "1");
                    Utils.playSound(block, "block.turtle_egg.break");
                    scheduleDone(block);
                    Utils.consumeItem(player, item);
                    return;
                }
                if (item.typeId === "peach:bacon_slice") {
                    Utils.setBlockState(block, "peach:mode", "1");
                    Utils.setBlockState(block, "peach:recipe", "2");
                    Utils.playSound(block, "extinguish.candle");
                    scheduleDone(block);
                    Utils.consumeItem(player, item);
                    return;
                }
                if (item.typeId === "peach:cassava") {
                    Utils.setBlockState(block, "peach:mode", "1");
                    Utils.setBlockState(block, "peach:recipe", "3");
                    Utils.playSound(block, "extinguish.candle");
                    scheduleDone(block);
                    Utils.consumeItem(player, item);
                    return;
                }
            }
            // ---------------- Give ----------------
            if (mode === "2") {
                const giveAndReset = (giveId) => {
                    Utils.giveItem(player, giveId);
                    Utils.setBlockState(block, "peach:recipe", "0");
                    Utils.setBlockState(block, "peach:mode", "0");
                    Utils.playSound(block, "random.pop");
                };

                if (recipe === "1" && item.typeId === "peach:skimmer") { giveAndReset("peach:fried_egg"); return; }
                if (recipe === "2" && item.typeId === "peach:skimmer") { giveAndReset("peach:fried_bacon"); return; }
                if (recipe === "3" && item.typeId === "peach:skimmer") { giveAndReset("peach:fried_cassava"); return; }
            }
            return;
        }
    });
});
