// KubeJS Server Script: Asbestos Proximity
const ASBESTOS_BLOCKS = [
    'neepmeat:asbestos',
    'neepmeat:asbestos_slab',
    'neepmeat:asbestos_wall',
    'neepmeat:asbestos_stairs'
];

const DETECTION_RANGE = 3;
let exposureData = {};

LevelEvents.tick(event => {
    const { level } = event;
    
    // Check exactly once every 20 ticks (1 second)
    if (level.time % 20 != 0) return;

    // Filter for loaded living entities
    let entities = level.getEntities().filter(e => e.living);
    
    entities.forEach(entity => {
        const id = entity.uuid.toString();
        let foundAsbestos = false;

        // Use BlockPos loop for compatibility
        for (let x = -DETECTION_RANGE; x <= DETECTION_RANGE; x++) {
            for (let y = -DETECTION_RANGE; y <= DETECTION_RANGE; y++) {
                for (let z = -DETECTION_RANGE; z <= DETECTION_RANGE; z++) {
                    let block = level.getBlock(entity.blockX + x, entity.blockY + y, entity.blockZ + z);
                    if (ASBESTOS_BLOCKS.includes(block.id)) {
                        foundAsbestos = true;
                        break;
                    }
                }
                if (foundAsbestos) break;
            }
            if (foundAsbestos) break;
        }

        if (foundAsbestos) {
            // Track exposure in seconds (20 ticks = 1 second increment)
            exposureData[id] = (exposureData[id] || 0) + 20;
            const exposure = exposureData[id];

            // Slowness (immediate, every second)
            entity.potionEffects.add('minecraft:slowness', 40, 1, false, false);

            // Nausea (after 5 seconds / 100 ticks)
            if (exposure >= 100) {
                entity.potionEffects.add('minecraft:nausea', 160, 1, false, false);
            }
            
            // Poison (after 15 seconds / 300 ticks)
            if (exposure >= 300) {
                entity.potionEffects.add('minecraft:poison', 300, 1, false, false);
            }
        } else {
            // Remove from tracking if they move away
            if (exposureData[id]) delete exposureData[id];
        }
    });
});

// Cleanup data to prevent memory leaks
EntityEvents.death(event => {
    delete exposureData[event.entity.uuid.toString()];
});

PlayerEvents.loggedOut(event => {
    delete exposureData[event.player.uuid.toString()];
});