import { system, world } from "@minecraft/server";
import { SettingsHandler } from "./settings";
function isWithinXZRadius(center, target, radiusSq) {
    const dx = center.x - target.x;
    const dz = center.z - target.z;
    return (dx * dx + dz * dz) <= radiusSq;
}
export function voidSpongePulse(block) {
    // Check if void sponge is enabled
    if (!SettingsHandler.isSpongeEnabled("voidSponge")) {
        const spongeDim = block.dimension;
        spongeDim.runCommand(`setblock ${block.location.x} ${block.location.y} ${block.location.z} air destroy`);
        // Notify nearby players
        const nearbyPlayers = spongeDim.getPlayers({ location: block.location, maxDistance: 10 });
        for (const player of nearbyPlayers) {
            player.sendMessage("§cVoid Sponge is disabled in settings!");
        }
        return;
    }
    const spongeLoc = block.location;
    const spongeDim = block.dimension;
    const dimId = spongeDim.id;
    const radiusSq = 50 * 50;
    for (const player of world.getPlayers()) {
        const pDim = player.dimension;
        if (pDim.id !== dimId)
            continue;
        const pLoc = player.location;
        if (!isWithinXZRadius(spongeLoc, pLoc, radiusSq))
            continue;
        const y = pLoc.y;
        const inVoid = (dimId === "minecraft:overworld" && y <= -64) ||
            (dimId === "minecraft:the_end" && y <= 0);
        (dimId === "minecraft:nether" && y <= 0);
        if (!inVoid)
            continue;
        // Teleport player on top of the sponge
        const teleportX = spongeLoc.x + 0.5;
        const teleportY = spongeLoc.y + 1;
        const teleportZ = spongeLoc.z + 0.5;
        player.teleport({ x: teleportX, y: teleportY, z: teleportZ }, { dimension: pDim, rotation: { x: 0, y: 90 } });
        // Particle at sponge
        spongeDim.spawnParticle("wildphire_spg:void_sponge_particle", {
            x: spongeLoc.x + 0.5,
            y: spongeLoc.y,
            z: spongeLoc.z + 0.5
        });
        // Title + message
        system.run(() => {
            player.onScreenDisplay.setTitle("§l§aSaved!");
            player.onScreenDisplay.updateSubtitle("§gThe Void Sponge Saved You!");
            player.sendMessage("§aYou were saved by the Void Sponge!§r\n§7You were teleported to the World spawn.");
        });
        // Delayed sound
        system.runTimeout(() => {
            spongeDim.playSound("conduit.activate", {
                x: teleportX,
                y: teleportY,
                z: teleportZ
            });
        }, 20);
    }
}
