import { world, system } from "@minecraft/server";
import { SettingsHandler } from "./settings";
// Map to track which players are affected by sticky sponges with timer info
const stickySpongeData = new Map();
// Start the interval to check for expired effects
system.runInterval(() => {
    stickySpongeAreaCheck();
}, 20); // Check every second (20 ticks)
export function stickySpongePlace(player, block) {
    // Check if sticky sponge is enabled
    if (!SettingsHandler.isSpongeEnabled("stickySponge")) {
        world.getDimension(block.dimension.id).runCommand(`setblock ${block.location.x} ${block.location.y} ${block.location.z} air destroy`);
        player.sendMessage("§cSticky Sponge is disabled in settings!");
        return;
    }
    const dimension = block.dimension;
    const spongeLocation = block.location;
    // Calculate end time (15 seconds from now)
    const currentTime = Date.now();
    const endTime = currentTime + 15000; // 15 seconds
    // Apply sticky effect to all players in 15 block radius except the placer
    const affectedPlayers = dimension.getPlayers({
        location: spongeLocation,
        maxDistance: 15
    });
    for (const affectedPlayer of affectedPlayers) {
        if (affectedPlayer.id !== player.id) {
            applyStickiness(affectedPlayer, player.id, spongeLocation, endTime);
        }
    }
    // Break the block instantly after placing
    system.runTimeout(() => {
        try {
            world.getDimension(block.dimension.id).runCommand(`setblock ${block.location.x} ${block.location.y} ${block.location.z} air destroy`);
        }
        catch (error) {
        }
    }, 20); // 1 second (20 ticks)
}
// New function for when called from custom component (block only)
export function stickySpongeOnPlace(block) {
    // Check if sticky sponge is enabled
    if (!SettingsHandler.isSpongeEnabled("stickySponge")) {
        world.getDimension(block.dimension.id).runCommand(`setblock ${block.location.x} ${block.location.y} ${block.location.z} air destroy`);
        // Notify nearby players
        const nearbyPlayers = world.getDimension(block.dimension.id).getPlayers({ location: block.location, maxDistance: 10 });
        for (const player of nearbyPlayers) {
            player.sendMessage("§cSticky Sponge is disabled in settings!");
        }
        return;
    }
    // Add a small delay to let the placement event process first
    system.runTimeout(() => {
        const dimension = block.dimension;
        const spongeLocation = block.location;
        // Calculate end time (15 seconds from now)
        const currentTime = Date.now();
        const endTime = currentTime + 15000; // 15 seconds
        // Get all players in range
        const allPlayers = dimension.getPlayers({
            location: spongeLocation,
            maxDistance: 15
        });
        // Find the closest player (most likely the placer) within 5 blocks
        let closestPlayer;
        let minDistance = 5; // Only consider players within 5 blocks as potential placers
        for (const checkPlayer of allPlayers) {
            const distance = Math.sqrt(Math.pow(checkPlayer.location.x - spongeLocation.x, 2) +
                Math.pow(checkPlayer.location.y - spongeLocation.y, 2) +
                Math.pow(checkPlayer.location.z - spongeLocation.z, 2));
            if (distance < minDistance) {
                minDistance = distance;
                closestPlayer = checkPlayer;
            }
        }
        // Apply sticky effect to all players except the closest one (likely the placer)
        for (const player of allPlayers) {
            // Check if player is already affected by a sticky sponge
            const isAlreadyAffected = stickySpongeData.has(player.id);
            if (!isAlreadyAffected && player.id !== closestPlayer?.id) {
                applyStickiness(player, closestPlayer?.id || "unknown", spongeLocation, endTime);
            }
        }
    }, 1); // Very small delay (1 tick)
    // Break the block instantly after placing
    system.runTimeout(() => {
        try {
            world.getDimension(block.dimension.id).runCommand(`setblock ${block.location.x} ${block.location.y} ${block.location.z} air destroy`);
        }
        catch (error) {
        }
    }, 20); // 1 second (20 ticks)
}
export function stickySpongeRemove(spongeLocation, dimension) {
    // This function is no longer needed since we use timers, but keeping for compatibility
    // The timer system will automatically remove effects
}
export function stickySpongePlayerJoin(player) {
    // Check if player has the sticky effect property and reapply it
    const isSticky = player.getDynamicProperty("sticky_effect");
    const placerId = player.getDynamicProperty("sticky_placer");
    const endTime = player.getDynamicProperty("sticky_end_time");
    if (isSticky && placerId && endTime) {
        const currentTime = Date.now();
        // Check if the effect should still be active
        if (currentTime < endTime) {
            // Restore the effect data and reapply restrictions
            stickySpongeData.set(player.id, {
                placer: placerId,
                spongeLocation: { x: 0, y: 0, z: 0 }, // Location doesn't matter for timer-based system
                endTime
            });
            system.run(() => {
                try {
                    player.runCommand("inputpermission set @s movement disabled");
                    player.runCommand("inputpermission set @s jump disabled");
                    // Calculate remaining time
                    const remainingTime = Math.ceil((endTime - currentTime) / 1000);
                    player.sendMessage(`§6Sticky effect restored! ${remainingTime} seconds remaining.`);
                    // Spawn sticky sponge particle on the affected player
                    player.dimension.spawnParticle("wildphire_spg:sticky_sponge_particle", player.location);
                }
                catch (error) {
                }
            });
            // Schedule removal for the remaining time
            const remainingTicks = Math.ceil((endTime - currentTime) / 50); // Convert ms to ticks
            system.runTimeout(() => {
                removeStickiness(player.id);
            }, remainingTicks);
        }
        else {
            // Effect has expired, clean up
            removeStickiness(player.id);
        }
    }
}
function applyStickiness(player, placerId, spongeLocation, endTime) {
    // Set dynamic properties to remember the effect
    player.setDynamicProperty("sticky_effect", true);
    player.setDynamicProperty("sticky_placer", placerId);
    player.setDynamicProperty("sticky_end_time", endTime);
    // Store in our tracking map
    stickySpongeData.set(player.id, { placer: placerId, spongeLocation, endTime });
    // Apply the input restrictions and spawn particle
    system.run(() => {
        try {
            player.runCommand("inputpermission set @s movement disabled");
            player.runCommand("inputpermission set @s jump disabled");
            player.sendMessage("§6You've been affected by a Sticky Sponge! Movement and jumping disabled for 15 seconds.");
            // Spawn initial sticky sponge particle on the affected player
            player.dimension.spawnParticle("wildphire_spg:sticky_sponge_particle", player.location);
        }
        catch (error) {
        }
    });
    // Schedule removal after 15 seconds
    system.runTimeout(() => {
        removeStickiness(player.id);
    }, 300); // 15 seconds (300 ticks)
}
function removeStickiness(playerId) {
    // Find the player
    const player = world.getAllPlayers().find(p => p.id === playerId);
    if (player) {
        // Remove dynamic properties
        player.setDynamicProperty("sticky_effect", undefined);
        player.setDynamicProperty("sticky_placer", undefined);
        player.setDynamicProperty("sticky_end_time", undefined);
        // Remove from tracking map
        stickySpongeData.delete(playerId);
        // Remove the input restrictions
        system.run(() => {
            try {
                player.runCommand("inputpermission set @s movement enabled");
                player.runCommand("inputpermission set @s jump enabled");
                player.sendMessage("§aSticky effect removed! Movement and jumping restored.");
            }
            catch (error) {
            }
        });
    }
    else {
        // Player is offline, just remove from tracking
        stickySpongeData.delete(playerId);
    }
}
// Timer-based cleanup function - checks for expired effects and spawns particles
export function stickySpongeAreaCheck() {
    const currentTime = Date.now();
    const expiredPlayers = [];
    // Check for expired effects and spawn particles for active ones
    for (const [playerId, data] of stickySpongeData.entries()) {
        if (currentTime >= data.endTime) {
            expiredPlayers.push(playerId);
        }
        else {
            // Effect is still active, spawn particle on the player
            const player = world.getAllPlayers().find(p => p.id === playerId);
            if (player) {
                try {
                    player.dimension.spawnParticle("wildphire_spg:sticky_sponge_particle", player.location);
                }
                catch (error) {
                    // Ignore particle spawn errors
                }
            }
        }
    }
    // Remove expired effects
    for (const playerId of expiredPlayers) {
        removeStickiness(playerId);
    }
}
