import { system, world } from "@minecraft/server";
import { SettingsHandler } from "./settings";
const heallingSpongeMap = new Map();
const itemTeleportCooldown = new Map();
const scheduledParticles = [];
// Cache for dimension access to avoid repeated lookups
const dimensionCache = new Map();
function getDimension(dimensionId) {
    if (!dimensionCache.has(dimensionId)) {
        dimensionCache.set(dimensionId, world.getDimension(dimensionId));
    }
    return dimensionCache.get(dimensionId);
}
function cleanupSpongeParticles(blockId) {
    // More efficient particle cleanup using filter
    const originalLength = scheduledParticles.length;
    let writeIndex = 0;
    for (let readIndex = 0; readIndex < originalLength; readIndex++) {
        if (scheduledParticles[readIndex].spongeId !== blockId) {
            scheduledParticles[writeIndex++] = scheduledParticles[readIndex];
        }
    }
    scheduledParticles.length = writeIndex;
}
export function antiEnderSpongePulse(block) {
    // Check if anti-ender sponge is enabled
    if (!SettingsHandler.isSpongeEnabled("antiEnderSponge")) {
        const dimension = getDimension(block.dimension.id);
        dimension.runCommand(`setblock ${block.location.x} ${block.location.y} ${block.location.z} air destroy`);
        // Notify nearby players
        const nearbyPlayers = dimension.getPlayers({ location: block.location, maxDistance: 10 });
        for (const player of nearbyPlayers) {
            player.sendMessage("§cAnti-Ender Sponge is disabled in settings!");
        }
        return;
    }
    const blockId = `${block.location.x}_${block.location.y}_${block.location.z}`;
    const dimension = getDimension(block.dimension.id);
    try {
        // Early exit if block doesn't exist
        const currentBlock = dimension.getBlock(block.location);
        if (!currentBlock || currentBlock.typeId !== block.typeId) {
            heallingSpongeMap.delete(blockId);
            cleanupSpongeParticles(blockId);
            return;
        }
        const now = Date.now();
        // Handle sponge timing
        if (!heallingSpongeMap.has(blockId)) {
            heallingSpongeMap.set(blockId, now + 45000); // 45 seconds
        }
        else {
            const expiryTime = heallingSpongeMap.get(blockId);
            if (expiryTime < now) {
                heallingSpongeMap.delete(blockId);
                dimension.runCommand(`setblock ${block.location.x} ${block.location.y} ${block.location.z} air destroy`);
                cleanupSpongeParticles(blockId);
                return;
            }
        }
        // Single entity query for better performance
        const allEntities = dimension.getEntities({
            maxDistance: 10,
            location: block.location
        });
        // Process entities in single loop
        const enderPearlsToTeleport = [];
        for (const entity of allEntities) {
            // Handle endermen
            if (entity.typeId === "minecraft:enderman") {
                try {
                    entity.kill();
                    dimension.playSound("mob.endermen.death", entity.location);
                    dimension.spawnParticle("minecraft:critical_hit_emitter", entity.location);
                }
                catch {
                    // Silent fail - continue processing
                }
            }
            // Handle dropped items
            else if (entity.typeId === "minecraft:item") {
                try {
                    const itemComponent = entity.getComponent("minecraft:item");
                    if (itemComponent?.itemStack.typeId === "minecraft:ender_pearl") {
                        const itemId = `${entity.location.x}_${entity.location.y}_${entity.location.z}_${entity.id}`;
                        const cooldownTime = itemTeleportCooldown.get(itemId);
                        if (!cooldownTime || cooldownTime < now) {
                            enderPearlsToTeleport.push({ entity, itemId });
                        }
                    }
                }
                catch {
                    // Silent fail - continue processing
                }
            }
        }
        // Process ender pearl teleportation
        if (enderPearlsToTeleport.length > 0) {
            const teleportLocation = {
                x: block.location.x + 0.5,
                y: block.location.y + 1.5,
                z: block.location.z + 0.5
            };
            for (const { entity, itemId } of enderPearlsToTeleport) {
                try {
                    itemTeleportCooldown.set(itemId, now + 2000);
                    entity.teleport(teleportLocation);
                    dimension.playSound("mob.endermen.portal", block.location);
                    dimension.spawnParticle("minecraft:portal", entity.location);
                }
                catch {
                    // Silent fail - continue processing
                }
            }
        }
        // Spawn immediate particles
        const particleLocation = {
            x: block.location.x + 0.5,
            y: block.location.y,
            z: block.location.z + 0.5
        };
        dimension.spawnParticle("wildphire_spg:antiEnder_ring_sponge_particle", particleLocation);
        dimension.spawnParticle("wildphire_spg:antiEnder_sponge_particle", particleLocation);
        // Queue delayed particles (reduced from 4 to 2 for efficiency)
        for (let i = 0; i < 2; i++) {
            scheduledParticles.push({
                location: block.location,
                dimension: block.dimension,
                spongeId: blockId
            });
        }
    }
    catch {
        // Skip this sponge if there's a critical error
        heallingSpongeMap.delete(blockId);
        cleanupSpongeParticles(blockId);
    }
}
// Optimized particle and cleanup system
system.runInterval(() => {
    // Process particles more efficiently
    if (scheduledParticles.length > 0) {
        const particle = scheduledParticles.shift();
        if (heallingSpongeMap.has(particle.spongeId)) {
            try {
                const dimension = getDimension(particle.dimension.id);
                // Check if the block still exists before spawning particles
                const currentBlock = dimension.getBlock(particle.location);
                if (currentBlock && currentBlock.typeId.includes("sponge")) {
                    dimension.spawnParticle("wildphire_spg:anti_ender_sponge_particle", {
                        x: particle.location.x + 0.5,
                        y: particle.location.y,
                        z: particle.location.z + 0.5
                    });
                }
                else {
                    // Block no longer exists, clean up this sponge
                    heallingSpongeMap.delete(particle.spongeId);
                    cleanupSpongeParticles(particle.spongeId);
                }
            }
            catch {
                // Silent fail - particle spawning error or block access error
                // Clean up the sponge if we can't access the block
                heallingSpongeMap.delete(particle.spongeId);
                cleanupSpongeParticles(particle.spongeId);
            }
        }
    }
    // Batch cleanup every 5 seconds (100 ticks) instead of every tick
    if (system.currentTick % 100 === 0) {
        const now = Date.now();
        const cutoff = now - 3000;
        // More efficient cleanup using for...of with early break
        const itemsToDelete = [];
        for (const [itemId, cooldownTime] of itemTeleportCooldown) {
            if (cooldownTime < cutoff) {
                itemsToDelete.push(itemId);
            }
        }
        // Batch delete
        for (const itemId of itemsToDelete) {
            itemTeleportCooldown.delete(itemId);
        }
        // Clear dimension cache periodically to prevent memory leaks
        if (dimensionCache.size > 10) {
            dimensionCache.clear();
        }
    }
}, 20);
