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

const Utils = {
  getPlayerEquipment(player) {
    return player.getComponent('equippable');
  },

  getSelectedItem(player) {
    const equip = this.getPlayerEquipment(player);
    return equip ? equip.getEquipment('Mainhand') : null;
  },

  giveItem(player, itemId, amount = 1) {
    try {
      const inv = player.getComponent("inventory").container;
      inv.addItem(new ItemStack(itemId, amount));
    } catch (e) {}
  },

  removeBlock(block) {
    try {
      block.setType("minecraft:air");
    } catch (e) {
      updateBlock(block, {});
    }
  },
};

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

      const typeId = block.typeId;
      let cleanName = typeId.replace("peach:", "").replace("_block", "");
      const itemId = `peach:${cleanName}`;

      Utils.giveItem(player, itemId, 1);
      Utils.removeBlock(block);
      try { player.playSound("random.pop"); } catch (e) {}
    }
  });
});
