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

// Listen for entity death events to spawn souls
world.afterEvents.entityDie.subscribe((event) => {
    const { deadEntity, damageSource } = event;
    
    // Early validation - check if entity is still valid and get location first
    if (!deadEntity || !deadEntity.isValid()) {
        return;
    }
    
    let deathLocation;
    let dimension;
    
    try {
        // Get the location and dimension before doing any other checks
        deathLocation = deadEntity.location;
        dimension = deadEntity.dimension;
    } catch (error) {
        return;
    }
    
    // Check if the dead entity is a mob (not a player or item)
    if (deadEntity.typeId !== "minecraft:player" && 
        deadEntity.typeId !== "minecraft:item" &&
        !deadEntity.typeId.includes("aft_soulhunters:soul")) {

        // 15% chance to spawn a soul
        if (Math.random() < 0.15) {
            // Spawn a soul at the death location
            try {
                dimension.spawnEntity("aft_soulhunters:soul", deathLocation);
            } catch (error) {
            }
        }
    }
});
