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

// Mapeo de ítems a números específicos y su estado correspondiente
const itemStateMap = {
    "enchanted_paperpets:arcos_spawn_egg": { state: "enchanted_paperpets:state_1", value: 1 },
    "enchanted_paperpets:fruit_spirit_spawn_egg": { state: "enchanted_paperpets:state_1", value: 2 },
    "enchanted_paperpets:cloudy_spawn_egg": { state: "enchanted_paperpets:state_1", value: 3 },
    "enchanted_paperpets:dinaris_spawn_egg": { state: "enchanted_paperpets:state_1", value: 4 },
    "enchanted_paperpets:dunes_spawn_egg": { state: "enchanted_paperpets:state_1", value: 5 },
    "enchanted_paperpets:auralis_spawn_egg": { state: "enchanted_paperpets:state_1", value: 6 },
    "enchanted_paperpets:jeppo_spawn_egg": { state: "enchanted_paperpets:state_1", value: 7 },
    "enchanted_paperpets:kino_spawn_egg": { state: "enchanted_paperpets:state_1", value: 8 },
    "enchanted_paperpets:lapis_spawn_egg": { state: "enchanted_paperpets:state_1", value: 9 },
    "enchanted_paperpets:lompy_spawn_egg": { state: "enchanted_paperpets:state_1", value: 10 },
    "enchanted_paperpets:mira_spawn_egg": { state: "enchanted_paperpets:state_1", value: 11 },
    "enchanted_paperpets:nova_spawn_egg": { state: "enchanted_paperpets:state_1", value: 12 },
    "enchanted_paperpets:otto_spawn_egg": { state: "enchanted_paperpets:state_1", value: 13 },
    "enchanted_paperpets:shade_spawn_egg": { state: "enchanted_paperpets:state_1", value: 14 },
    "enchanted_paperpets:solara_spawn_egg": { state: "enchanted_paperpets:state_1", value: 15 },
    "enchanted_paperpets:wando_spawn_egg": { state: "enchanted_paperpets:state_2", value: 16 },
    "enchanted_paperpets:zara_spawn_egg": { state: "enchanted_paperpets:state_2", value: 17 }
};

// Mapa inverso para recuperar el ítem a partir del estado
const stateItemMap = {};
for (const [item, { state, value }] of Object.entries(itemStateMap)) {
    stateItemMap[`${state}-${value}`] = item;
}

world.beforeEvents.worldInitialize.subscribe((data) => {
    const { blockComponentRegistry } = data;

    blockComponentRegistry.registerCustomComponent("enchanted_paperpets:state_1", {
        onPlayerInteract: (data) => {
            const block = data.block;
            const player = data.player;

            const equipment = player.getComponent("minecraft:equippable");
            if (!equipment) return;

            const mainHandItem = equipment.getEquipment(EquipmentSlot.Mainhand);
            if (!mainHandItem) return;

            const itemId = mainHandItem.typeId;
            if (!itemStateMap[itemId]) return;

            // Obtener el estado actual del bloque
            const currentState1 = block.permutation.getState("enchanted_paperpets:state_1") ?? 0;
            const currentState2 = block.permutation.getState("enchanted_paperpets:state_2") ?? 0;

            // Determinar qué estado está en uso
            const currentState = currentState1 !== 0 ? "enchanted_paperpets:state_1" : "enchanted_paperpets:state_2";
            const currentValue = currentState1 !== 0 ? currentState1 : currentState2;

            // Dar el ítem anterior al jugador
            const previousItem = stateItemMap[`${currentState}-${currentValue}`];
            if (previousItem) {
                player.runCommand(`give @s ${previousItem}`);
            }

            // Remover un ítem de la mano del jugador
            player.runCommand(`clear @s ${itemId} 0 1`);

            // Obtener el nuevo estado y actualizar el bloque
            const { state, value } = itemStateMap[itemId];
            let newPermutation = block.permutation.withState(state, value);

            // Resetear el otro estado
            if (state === "enchanted_paperpets:state_1") {
                newPermutation = newPermutation.withState("enchanted_paperpets:state_2", 0);
            } else {
                newPermutation = newPermutation.withState("enchanted_paperpets:state_1", 0);
            }

            block.setPermutation(newPermutation);
        }
    });
});


// Evento cuando un jugador rompe un bloque
world.beforeEvents.playerBreakBlock.subscribe((data) => {
    const { block, player } = data;

    // Verifica si el bloque roto es enchanted_paperpets:marco
    if (block.typeId !== "enchanted_paperpets:marco") return;

    // Intentar obtener el estado del bloque
    try {
        const permutation = block.permutation;

        if (!permutation) return;

        const currentState1 = permutation.getState("enchanted_paperpets:state_1") ?? 0;
        const currentState2 = permutation.getState("enchanted_paperpets:state_2") ?? 0;

        // Determinar qué estado estaba en uso
        const currentState = currentState1 !== 0 ? "enchanted_paperpets:state_1" : "enchanted_paperpets:state_2";
        const currentValue = currentState1 !== 0 ? currentState1 : currentState2;

        // Obtener el ítem correspondiente al estado actual
        const itemToGive = stateItemMap[`${currentState}-${currentValue}`];

        if (itemToGive) {
            player.runCommandAsync(`give @s ${itemToGive}`);
        }
    } catch (error) {
        console.warn(`Error al procesar playerBreakBlock: ${error}`);
    }
});