import { Server } from "../../../libs/Core/index.js";


Server.scriptEventManager.registerEvent('sculker_mine_explode', (e) => {
    const entity = e.sourceEntity;
    const dimension = entity.dimension;
    const location = entity.location;
    const radius = 3.15;

    if (entity.typeId !== 'plank_waao:sculker_mine') return;

    // particle
    [
        'plank_waao:sculker_mine_circle',
        'plank_waao:sculker_mine_explosion_impact',
        'plank_waao:sculker_mine_explosion_ring',
        'plank_waao:sculker_mine_light_explosion'
    ].forEach((p) => {
        dimension.spawnParticle(p, location);
    })

    // block breaking
    for (let x = location.x - radius; x <= location.x + radius; x++) {
        for (let y = location.y - radius; y <= location.y + radius; y++) {
            for (let z = location.z - radius; z <= location.z + radius; z++) {
                let distance = Math.sqrt((x - location.x) ** 2 + (y - location.y) ** 2 + (z - location.z) ** 2);

                if (distance <= radius) {
                    try {
                        const block = dimension.getBlock({ x, y, z });
                        if (!block) continue;

                        if (block.typeId !== 'minecraft:bedrock') {
                            block.setType('minecraft:air');
                        }
                    } catch { }
                }
            }
        }
    }
    // sound
    dimension.playSound('mob.plank_waao.sculker_mine.explosion', location);

    entity.remove();

    // knockback and damage
    const baseDamage = 20;
    const hitEntities = dimension.getEntities({
        location: location,
        maxDistance: radius
    });

    for (const entity of hitEntities) {
        if (!entity || !entity.isValid()) continue;

        const knockbackDirection = {
            x: entity.location.x - location.x,
            z: entity.location.z - location.z
        };

        const magnitude = Math.sqrt(knockbackDirection.x ** 2 + knockbackDirection.z ** 2);

        if (magnitude > 0) {
            const normalizedDirection = {
                x: knockbackDirection.x / magnitude,
                z: knockbackDirection.z / magnitude
            };

            entity.applyKnockback(normalizedDirection.x, normalizedDirection.z, 1.6, 0.8);

            const distanceFactor = 1 - (magnitude / radius);
            const damage = baseDamage * distanceFactor;

            // Apply damage to the entity
            entity.applyDamage(damage);
        } else {
            entity.applyKnockback(0, 0, 0, 0.8);
            entity.applyDamage(baseDamage);
        }
    };
});