import { world } from '@minecraft/server';

const POPPY_ID = "mebesm:poppy";
const KISSY_MISSY_ID = "mebesm:kissy_missy";
const KISSY_POPPY_ID = "mebesm:kissy_missy_poppy";
const POPPY_INTERACTION_RADIUS = 3;

function handlePoppyHit(event) {
    const { damagingEntity, hitEntity } = event;

    if (damagingEntity.typeId !== "minecraft:player") return;
    if (hitEntity.typeId !== POPPY_ID) return;

    try {
        const dimension = hitEntity.dimension;
        const poppyLocation = hitEntity.location;

        const nearbyKissies = dimension.getEntities({
            type: KISSY_MISSY_ID,
            location: poppyLocation,
            maxDistance: POPPY_INTERACTION_RADIUS
        });

        if (nearbyKissies.length > 0) {
            const targetKissy = nearbyKissies[0];

            dimension.spawnEntity(KISSY_POPPY_ID, targetKissy.location);
            targetKissy.remove();
            hitEntity.remove();
        }
    } catch (e) {
        console.error(`[POPPY] ${e}`);
    }
}

world.afterEvents.entityHitEntity.subscribe(handlePoppyHit);