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

const DETECTION_RANGE = 1;
let exposureData = {};

PlayerEvents.tick(event => {
    const { player, level } = event;

    // Check exactly once every 20 ticks (1 second) to save performance
    if (level.time % 20 != 0) return;

    const id = player.uuid.toString();

    // Check for Gas Mask (Immunity)
    if (player.headArmorItem.id === 'createbigcannons:gas_mask') {
        if (exposureData[id]) delete exposureData[id];
        return;
    }

    let foundAsbestos = false;

    // Proximity detection loop
    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(player.blockX + x, player.blockY + y, player.blockZ + z);
                if (ASBESTOS_BLOCKS.includes(block.id)) {
                    foundAsbestos = true;
                    break;
                }
            }
            if (foundAsbestos) break;
        }
        if (foundAsbestos) break;
    }

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

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

        // Nausea (after 5 seconds / 100 ticks)
        if (exposure >= 100) {
            player.potionEffects.add('minecraft:nausea', 160, 1, false, false);
        }
        
        // Poison (after 15 seconds / 300 ticks)
        if (exposure >= 300) {
            player.potionEffects.add('minecraft:poison', 300, 1, false, false);
        }
    } else {
        // Clear data if they are no longer near asbestos
        if (exposureData[id]) delete exposureData[id];
    }
});

// Cleanup data when player leaves
PlayerEvents.loggedOut(event => {
    delete exposureData[event.player.uuid.toString()];
});
