import { MolangVariableMap, system } from "@minecraft/server";
import { Server } from "../../../libs/Core/index.js";


// @todo: add a delay
Server.scriptEventManager.registerEvent('sculk_bug_adult_death', (e) => {
    const bug = e.sourceEntity;
    if (!bug || !bug.isValid()) return;
    const dimension = bug.dimension;

    const knockbackStrength = 1.8;
    const knockbackY = 0.8;

    const viewDirection = bug.getViewDirection();

    for (let i = 0; i < 5; i++) {
        const babyBug = dimension.spawnEntity('plank_waao:sculk_bug_baby', bug.location);

        if (babyBug && babyBug.isValid()) {
            const variance = 0.2;
            const knockbackDirection = {
                x: viewDirection.x + (Math.random() * variance - variance / 2),
                z: viewDirection.z + (Math.random() * variance - variance / 2)
            };

            // Normalize the knockback direction to maintain consistent strength
            const magnitude = Math.sqrt(knockbackDirection.x ** 2 + knockbackDirection.z ** 2);
            const normalizedDirection = {
                x: knockbackDirection.x / magnitude,
                z: knockbackDirection.z / magnitude
            };

            // Apply knockback in the slightly varied direction
            babyBug.applyKnockback(normalizedDirection.x, normalizedDirection.z, knockbackStrength, knockbackY);
        }
    }

    system.runTimeout(() => {
        if (bug && bug.isValid()) {
            const variableMap = new MolangVariableMap();
            variableMap.setVector3('aabb', { x: 1.5, y: 1.0, z: 1.5 });
            dimension.spawnParticle('minecraft:death_explosion_emitter', bug.location, variableMap);
            bug.remove();
        }
    }, 30);
});