import { world, ItemStack, GameMode } 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) {
        updateBlock(block, { [stateName]: value });
    }
};

const basketItems = {
    "peach:blueberry": "blueberry",
    "peach:strawberry": "strawberry",
    "peach:orange": "orange",
    "minecraft:apple": "apple",
    "minecraft:sweet_berries": "berries"
};

world.beforeEvents.worldInitialize.subscribe(pch => {
    pch.blockComponentRegistry.registerCustomComponent('peach:basket_logic', {
        onPlayerInteract: e => {
            const { player, block } = e;
            const selectedItem = Utils.getSelectedItem(player);
            const content = block.permutation.getState("peach:basket_content");

            if (content === "empty") {
                if (!selectedItem) return;

                const stateValue = basketItems[selectedItem.typeId];
                if (stateValue) {
                    Utils.consumeItem(player, selectedItem);
                    Utils.setBlockState(block, "peach:basket_content", stateValue);
                    player.playSound("use.moss");
                }
                return;
            }

            if (content !== "empty") {
                let itemId = Object.keys(basketItems).find(k => basketItems[k] === content);
                if (itemId) {
                    player.getComponent("inventory").container.addItem(new ItemStack(itemId));
                    Utils.setBlockState(block, "peach:basket_content", "empty");
                    player.playSound("random.pop");
                }
                return;
            }
        }
    });
});