ServerEvents.tick(event => {
    // Check every second
    if (event.server.tickCount % 20 != 0) return;
    let players = event.server.getPlayers();
    if (players.isEmpty()) return;
    event.server.entities.forEach(entity => {
        if (!entity.living || entity.type == 'minecraft:item_display') return;
       
        // --- 1. PROXIMITY CHECK (12 Blocks) ---
        let isVeryNear = false;
        for (let p of players) {
            if (p.distanceToEntity(entity) < 12) {
                isVeryNear = true;
                break;
            }
        }
        let id = entity.type.toString();
        // 2. EXCLUSION: Humanoids (they already show the shield model when blocking)
        let isHumanoid = (
            id.includes('zombie') || id.includes('skeleton') ||
            id.includes('piglin') || id.includes('player') ||
            id.includes('husk') || id.includes('drowned') ||
            id.includes('pillager') || id.includes('vindicator')
        );
        // 3. BLOCKING DETECTION (only show icon while actively blocking with a shield)
        let isBlocking = entity.isBlocking();

        // LOGIC GATE: Must be Near, Must NOT be Humanoid, Must be ACTIVELY BLOCKING
        if (isVeryNear && !isHumanoid && isBlocking) {
            if (!entity.tags.contains('has_shield_icon')) {
                // Higher offset to clear health bars (adjust ±0.2 if needed for your specific health bar mod)
                let heightOffset = entity.bbHeight + 1.0;
                let display = entity.level.createEntity('minecraft:item_display');
                display.setPosition(entity.x, entity.y, entity.z);
               
                // Slightly smaller scale + higher position + glow/brightness preserved
                display.mergeNbt(`{has_glowing:1b,glow_color_override:16777215,brightness:{block:15,sky:15},item:{id:"minecraft:shield",Count:1b},billboard:"center",transformation:{left_rotation:[0f,0f,0f,1f],right_rotation:[0f,1f,0f,0f],translation:[0f,${heightOffset}f,0f],scale:[0.25f,0.25f,0.25f]}}`);
               
                display.spawn();
                display.startRiding(entity, true);
                entity.addTag('has_shield_icon');
                display.addTag('shield_icon_entity');
            }
        } else {
            // AUTO-DISCARD: If player walks away, mob stops blocking, etc.
            if (entity.tags.contains('has_shield_icon')) {
                entity.passengers.forEach(p => {
                    if (p.tags.contains('shield_icon_entity')) p.discard();
                });
                entity.removeTag('has_shield_icon');
            }
        }
    });
});

// CLEANUP ON DEATH
EntityEvents.death(event => {
    if (event.entity.tags.contains('has_shield_icon')) {
        event.entity.passengers.forEach(p => { 
            if (p.tags.contains('shield_icon_entity')) p.discard(); 
        });
    }
});