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

const Utils = {
    getPlayerEquipment(player) {
        return player.getComponent('equippable');
    },
    getSelectedItem(player) {
        const equip = this.getPlayerEquipment(player);
        return equip ? equip.getEquipment('Mainhand') : null;
    },
    consumeItem(player, item) {
        if (player.getGameMode() === GameMode.creative) return;
        const equip = this.getPlayerEquipment(player);
        consumeEquipped(equip, item);
    },
    setBlockState(block, stateName, value) {
        try {
            const newPerm = block.permutation.withState(stateName, value);
            block.setPermutation(newPerm);
        } catch (err) {
            updateBlock(block, { [stateName]: value });
        }
    },
    giveItem(player, id) {
        try {
            player.getComponent("inventory").container.addItem(new ItemStack(id));
        } 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 scheduleStage5(block) {
    try {
        const delayMs = 1200;
        system.runTimeout(() => {
            try {
                const blockAfterDelay = block.dimension.getBlock(block.location);
                if (blockAfterDelay && blockAfterDelay.permutation.getState("peach:stage") === "4") {
                    updateBlock(blockAfterDelay, { "peach:stage": "5" });
                    Utils.spawnParticle(block, "minecraft:campfire_smoke_particle");
                    blockAfterDelay.dimension.playSound("note.bell", blockAfterDelay.location);
                }
            } catch (err) {}
        }, delayMs);
    } catch (e) {}
}

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

            const equip = player.getComponent("equippable");
            const item = equip?.getEquipment("Mainhand");

            const stage = block.permutation.getState("peach:stage");
            const flavor = block.permutation.getState("peach:flavors");
            const mix = block.permutation.getState("peach:mixes");
            const required = block.permutation.getState("peach:required");

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

            // ---------------- STAGE 3 -> 4 ----------------
            if (stage === "3" && player.isSneaking) {
                if (parseInt(required) > 0 || (parseInt(flavor) === 0 && parseInt(mix) === 0)) {
                    block.dimension.playSound("note.bassattack", block.location);
                    return;
                }
            updateBlock(block, { "peach:stage": "4" });
            block.dimension.playSound("note.flute", block.location);
            scheduleStage5(block);
            return;
        }

            // ---------------- STAGE 0 ----------------
            const allZero = stage === "0" && flavor === "0" && mix === "0" && required === "0";

            if (allZero && item.typeId === "peach:ice_balls") {
                Utils.setBlockState(block, "peach:stage", "1");
                Utils.playSound(block, "random.pop");
                if (player.getGameMode() !== GameMode.creative) Utils.consumeItem(player, item);
                return;
            }

            if (allZero && item.typeId === "peach:cream") {
                Utils.setBlockState(block, "peach:stage", "2");
                Utils.playSound(block, "random.pop");
                if (player.getGameMode() !== GameMode.creative) Utils.consumeItem(player, item);
                return;
            }

            // ---------------- STAGE 1 -> 3 ----------------
            if (stage === "1" && flavor === "0" && mix === "0" && required === "0" && item.typeId === "peach:cream") {
                Utils.setBlockState(block, "peach:stage", "3");
                Utils.playSound(block, "random.pop");
                if (player.getGameMode() !== GameMode.creative) Utils.consumeItem(player, item);
                return;
            }

            // ---------------- STAGE 2 -> 3 ----------------
            if (stage === "2" && flavor === "0" && mix === "0" && required === "0" && item.typeId === "peach:ice_balls") {
                Utils.setBlockState(block, "peach:stage", "3");
                Utils.playSound(block, "random.pop");
                if (player.getGameMode() !== GameMode.creative) Utils.consumeItem(player, item);
                return;
            }

            // ---------------- STAGE 3 ----------------
            const flavorMap = {
                "peach:blueberry": "1",
                "minecraft:melon_slice": "2",
                "peach:chocolate_powder": "3",
                "peach:mint": "4",
                "minecraft:cookie": "5",
                "peach:grape": "6",
                "peach:guava": "7",
                "peach:mango": "8",
                "peach:passion_fruit": "9",
                "peach:peach": "10",
                "peach:strawberry": "11",
                "peach:vanilla_essence": "12"
            };

            if (stage === "3" && flavor === "0" && mix === "0" && required === "0" && flavorMap[item.typeId]) {
                Utils.setBlockState(block, "peach:flavors", flavorMap[item.typeId]);
                Utils.playSound(block, "random.pop");
                if (player.getGameMode() !== GameMode.creative) Utils.consumeItem(player, item);
                return;
            }

            // ---------------- MIXES ----------------
            if (stage === "3" && flavor === "4" && mix === "0" && required === "0" && item.typeId === "peach:chocolate_powder") {
                Utils.setBlockState(block, "peach:mixes", "1");
                Utils.setBlockState(block, "peach:flavors", "0");
                Utils.playSound(block, "random.pop");
                if (player.getGameMode() !== GameMode.creative) Utils.consumeItem(player, item);
                return;
            }

            if (stage === "3" && flavor === "3" && mix === "0" && required === "0" && item.typeId === "peach:mint") {
                Utils.setBlockState(block, "peach:mixes", "1");
                Utils.setBlockState(block, "peach:flavors", "0");
                Utils.playSound(block, "random.pop");
                if (player.getGameMode() !== GameMode.creative) Utils.consumeItem(player, item);
                return;
            }

            if (stage === "3" && flavor === "7" && mix === "0" && required === "0" && item.typeId === "peach:mozzarella") {
                Utils.setBlockState(block, "peach:mixes", "3");
                Utils.setBlockState(block, "peach:flavors", "0");
                Utils.playSound(block, "random.pop");
                if (player.getGameMode() !== GameMode.creative) Utils.consumeItem(player, item);
                return;
            }

            if (stage === "3" && flavor === "0" && mix === "0" && required === "1" && item.typeId === "peach:guava") {
                Utils.setBlockState(block, "peach:mixes", "3");
                Utils.setBlockState(block, "peach:required", "0");
                Utils.playSound(block, "random.pop");
                if (player.getGameMode() !== GameMode.creative) Utils.consumeItem(player, item);
                return;
            }

            if (stage === "3" && flavor === "0" && mix === "0" && required === "2" && item.typeId === "peach:vanilla_essence") {
                Utils.setBlockState(block, "peach:mixes", "2");
                Utils.setBlockState(block, "peach:required", "0");
                Utils.playSound(block, "random.pop");
                if (player.getGameMode() !== GameMode.creative) Utils.consumeItem(player, item);
                return;
            }

            if (stage === "3" && flavor === "0" && mix === "0" && required === "3" && item.typeId === "peach:strawberry") {
                Utils.setBlockState(block, "peach:mixes", "2");
                Utils.setBlockState(block, "peach:required", "0");
                Utils.playSound(block, "random.pop");
                if (player.getGameMode() !== GameMode.creative) Utils.consumeItem(player, item);
                return;
            }

            if (stage === "3" && flavor === "0" && mix === "0" && required === "4" && item.typeId === "peach:chocolate_powder") {
                Utils.setBlockState(block, "peach:mixes", "2");
                Utils.setBlockState(block, "peach:required", "0");
                Utils.playSound(block, "random.pop");
                if (player.getGameMode() !== GameMode.creative) Utils.consumeItem(player, item);
                return;
            }

            // ---------------- REQUIRED ----------------
            if (stage === "3" && flavor === "3" && mix === "0" && required === "0" && item.typeId === "peach:strawberry") {
                Utils.setBlockState(block, "peach:required", "2");
                Utils.setBlockState(block, "peach:flavors", "0");
                Utils.playSound(block, "random.pop");
                if (player.getGameMode() !== GameMode.creative) Utils.consumeItem(player, item);
                return;
            }

            if (stage === "3" && flavor === "3" && mix === "0" && required === "0" && item.typeId === "peach:vanilla_essence") {
                Utils.setBlockState(block, "peach:required", "3");
                Utils.setBlockState(block, "peach:flavors", "0");
                Utils.playSound(block, "random.pop");
                if (player.getGameMode() !== GameMode.creative) Utils.consumeItem(player, item);
                return;
            }

            if (stage === "3" && flavor === "11" && mix === "0" && required === "0" && item.typeId === "peach:chocolate_powder") {
                Utils.setBlockState(block, "peach:required", "2");
                Utils.setBlockState(block, "peach:flavors", "0");
                Utils.playSound(block, "random.pop");
                if (player.getGameMode() !== GameMode.creative) Utils.consumeItem(player, item);
                return;
            }

            if (stage === "3" && flavor === "11" && mix === "0" && required === "0" && item.typeId === "peach:vanilla_essence") {
                Utils.setBlockState(block, "peach:required", "4");
                Utils.setBlockState(block, "peach:flavors", "0");
                Utils.playSound(block, "random.pop");
                if (player.getGameMode() !== GameMode.creative) Utils.consumeItem(player, item);
                return;
            }

            if (stage === "3" && flavor === "12" && mix === "0" && required === "0" && item.typeId === "peach:strawberry") {
                Utils.setBlockState(block, "peach:required", "4");
                Utils.setBlockState(block, "peach:flavors", "0");
                Utils.playSound(block, "random.pop");
                if (player.getGameMode() !== GameMode.creative) Utils.consumeItem(player, item);
                return;
            }

            if (stage === "3" && flavor === "12" && mix === "0" && required === "0" && item.typeId === "peach:chocolate_powder") {
                Utils.setBlockState(block, "peach:required", "3");
                Utils.setBlockState(block, "peach:flavors", "0");
                Utils.playSound(block, "random.pop");
                if (player.getGameMode() !== GameMode.creative) Utils.consumeItem(player, item);
                return;
            }

            if (stage === "3" && flavor === "0" && mix === "0" && required === "0" && item.typeId === "peach:mozzarella") {
                Utils.setBlockState(block, "peach:required", "1");
                Utils.playSound(block, "random.pop");
                if (player.getGameMode() !== GameMode.creative) Utils.consumeItem(player, item);
                return;
            }

            // ---------------- STAGE 5 -> Tins ----------------
            if (stage === "5" && item?.typeId === "peach:tin" && (flavor !== "0" || mix !== "0")) {
                const selectedItem = Utils.getSelectedItem(player);
                let newTin = null;
                if (mix !== "0") {
                    const mixTins = [
                        "peach:tin_chocomint",
                        "peach:tin_neapolitan",
                        "peach:tin_cheese_and_guava"
                    ];
                    const idx = parseInt(mix, 10) - 1;
                    newTin = mixTins[idx] || null;
                } else if (flavor !== "0") {
                    const flavorTins = [
                        "peach:tin_blueberry",
                        "peach:tin_watermelon",
                        "peach:tin_chocolate",
                        "peach:tin_mint",
                        "peach:tin_cookies_and_cream",
                        "peach:tin_grape",
                        "peach:tin_guava",
                        "peach:tin_mango",
                        "peach:tin_passion_fruit",
                        "peach:tin_peach",
                        "peach:tin_strawberry",
                        "peach:tin_vanilla"
                    ];
                    const idx = parseInt(flavor, 10) - 1;
                    newTin = flavorTins[idx] || null;
                }
                if (!newTin) return;
                if (player.getGameMode() !== GameMode.creative) {
                    Utils.consumeItem(player, selectedItem);
                }
                Utils.giveItem(player, newTin);
                Utils.setBlockState(block, "peach:stage", "0");
                Utils.setBlockState(block, "peach:flavors", "0");
                Utils.setBlockState(block, "peach:mixes", "0");
                Utils.setBlockState(block, "peach:required", "0");

                Utils.playSound(block, "random.pop");
                return;
            }

        }
    });
});
