import { world } from "@minecraft/server";
import { CONFIG } from "../config.js";
import { pickRandom } from "../utils/random.js";

export function registerSoilSpawn() {
  world.afterEvents.playerBreakBlock.subscribe((ev) => {
    const player = ev.player;
    if (!player || player.getGameMode() !== "Survival") return;

    const inv = player.getComponent("inventory");
     const item = player.getComponent('inventory')?.container.getItem(ev.player.selectedSlotIndex);
    const ench = item?.getComponent("enchantable") ?? null;
    

    if (ench?.getEnchantment("silk_touch")) return;

    // Bloque válido
    const blockTypeId = ev.brokenBlockPermutation?.type?.id;
    if (!blockTypeId || !CONFIG.blocks.has(blockTypeId)) return;

    // Probabilidad
    if (Math.random() >= CONFIG.chance) return;

    // Spawn
    const mobId = pickRandom(CONFIG.mobs);
    if (!mobId) return;

    let loc = ev.block.location;
    if (CONFIG.spawnCentered) {
      loc = { x: loc.x + 0.5, y: loc.y + 1, z: loc.z + 0.5 };
    }

    try {
      ev.dimension.spawnEntity(mobId, loc);
    } catch { }
  });
}
