import { world, system, BlockPermutation } from '@minecraft/server';

const WOOD_BLOCKS = [
    "minecraft:oak_log",
    "minecraft:stripped_oak_log",
    "minecraft:spruce_log",
    "minecraft:stripped_spruce_log",
    "minecraft:birch_log",
    "minecraft:stripped_birch_log",
    "minecraft:jungle_log",
    "minecraft:stripped_jungle_log",
    "minecraft:acacia_log",
    "minecraft:stripped_acacia_log",
    "minecraft:dark_oak_log",
    "minecraft:stripped_dark_oak_log",
    "minecraft:mangrove_log",
    "minecraft:stripped_mangrove_log",
    "minecraft:cherry_log",
    "minecraft:stripped_cherry_log",
    "minecraft:pale_oak_log",
    "minecraft:stripped_pale_oak_log",
    "minecraft:crimson_stem",
    "minecraft:stripped_crimson_stem",
    "minecraft:warped_stem",
    "minecraft:stripped_warped_stem",
    "pu_biomes:enchanted_log",
    "pu_biomes:stripped_enchanted_log",
    "pu_biomes:lunar_log",
    "pu_biomes:stripped_lunar_log",
    "pu_biomes:hollow_horror_log",
    "pu_biomes:sky_log",
    "pu_biomes:stripped_sky_log",
    "pu_biomes:toxic_log",
    "pu_biomes:stripped_toxic_log",
    "pu_biomes:ground_orange_log",
    "pu_biomes:horror_log",
    "pu_biomes:stripped_horror_log",
    "pu_biomes:orange_log",
    "pu_biomes:stripped_orange_log",
    "pu_biomes:redwood_log",
    "pu_biomes:red_log",
    "pu_biomes:stripped_red_log",
    "pu_biomes:hollow_red_log",
    "pu_biomes:ground_horror_log",
    "pu_biomes:hollow_toxic_log",
    "pu_biomes:hollow_sky_log",
    "pu_biomes:hollow_orange_log",
    "pu_biomes:hollow_enchanted_log",
    "pu_biomes:hollow_redwood_log",
    "pu_biomes:hollow_lunar_log",
    "pu_biomes:ground_toxic_log",
    "pu_biomes:ground_sky_log",
    "pu_biomes:ground_red_log",
    "pu_biomes:ground_enchanted_log",
    "pu_biomes:ground_redwood_log",
    "pu_biomes:ground_lunar_log"
]

const POISON_ENTITIES = [
    "pu_biomes:rat",
    "pu_biomes:cobra_snake",
    "pu_biomes:scorpion",
    "pu_biomes:toxic_slime"
]

world.afterEvents.playerInteractWithEntity.subscribe(eventData => {
    const trader = eventData.target;
    if (trader.typeId === "pu_biomes:islander" || trader.typeId === "pu_biomes:mushroom_villager"){
        trader.triggerEvent("pu_biomes:trading")
        system.runTimeout(() => {
            if (trader.isValid()) trader?.triggerEvent("pu_biomes:not_trading");
        }, 500);
    }
});

world.afterEvents.entityHitEntity.subscribe(eventData => {
    const attacker = eventData.damagingEntity;
    if (POISON_ENTITIES.includes(attacker.typeId)) {
        const hitEntity = eventData.hitEntity;
        hitEntity.runCommand("effect @s poison 10 0 true");
    }
    if (attacker.typeId === "pu_biomes:centipede") {
        if (Math.random() < 0.1) {
            const hitEntity = eventData.hitEntity;
            hitEntity.addEffect('poison', 60, {amplifier: 1});
        }
    }
    if (attacker.typeId === "pu_biomes:swamp_creature") {
        if (Math.random() < 0.25) {
            const hitEntity = eventData.hitEntity;
            hitEntity.addEffect('poison', 60, {amplifier: 1});
        }
    }
    if (attacker.typeId === "pu_biomes:large_infected_mushroom") {
        if (Math.random() < 0.5) {
            const hitEntity = eventData.hitEntity;
            hitEntity.addEffect('poison', 60, {amplifier: 1});
        }
    }
    if (attacker.typeId === "pu_biomes:swamp_trap") {
        if (Math.random() < 0.5) {
            const hitEntity = eventData.hitEntity;
            hitEntity.addEffect('slowness', 40, {amplifier: 0});
        }
    }
    if (attacker.typeId === "pu_biomes:plant_golem") {
        const hitEntity = eventData.hitEntity;
        const viewDirection = attacker.getViewDirection();
        hitEntity?.applyKnockback(viewDirection.x, viewDirection.z, 0.8, (Math.max(Math.min(-viewDirection.y * 2, 0.5), -1) + 1) * 0.60);
    }
    if (attacker.typeId === "pu_biomes:lava_golem") {
        const hitEntity = eventData.hitEntity;
        const viewDirection = attacker.getViewDirection();
        hitEntity?.applyKnockback(viewDirection.x, viewDirection.z, 0.8, (Math.max(Math.min(-viewDirection.y * 2, 0.5), -1) + 1) * 0.60);
        hitEntity?.setOnFire(5);
    }
    if (attacker.typeId === "minecraft:player") {
        const hitEntity = eventData.hitEntity;
        if (hitEntity.typeId === "pu_biomes:islander") {
            const entitiesAround = hitEntity.dimension.getEntities({
                location: hitEntity.location,
                maxDistance: 32
            });

            entitiesAround.forEach(e => {
                if(e.typeId === "pu_biomes:cloud_monster") {
                    e.triggerEvent("pu_biomes:defend_islanders");
                    system.runTimeout(() => {
                        if (e.isValid())
                        e?.triggerEvent("pu_biomes:normal_attack_pattern");
                    }, 600);
                }
            });

        }
    }
});

system.afterEvents.scriptEventReceive.subscribe((event)=>{
    if (event.id === "pu_biomes:wind_dragon_signal") {
        const wind_dragon = event.sourceEntity;
        const rideableComponent = wind_dragon.getComponent("minecraft:rideable");
        if (rideableComponent) {
            const riders = rideableComponent.getRiders();
            if (riders.length > 0) {
                wind_dragon.setDynamicProperty("pu_biomes_has_rider", true);
                const rider = riders[0];
                if (rider.isValid()) {
                    if (!wind_dragon.isOnGround) {
                        system.runTimeout(() => {
                            if (!wind_dragon.isOnGround) {
                                wind_dragon.addEffect("speed", 10, {amplifier: 15, showParticles: false});
                            }
                        }, 20);
                    } else {
                        wind_dragon.removeEffect('speed');
                    }
                    if (rider.isJumping) {
                        wind_dragon.addEffect("levitation", 20, {amplifier: 1, showParticles: false});
                    } else {
                        if (!wind_dragon.isOnGround) {
                            wind_dragon.addEffect("slow_falling", 20, {amplifier: 1, showParticles: false});
                        }
                    }   
                }
            } else {
                if (wind_dragon.getDynamicProperty("pu_biomes_has_rider")) {
                    if (!wind_dragon.isOnGround) {
                        wind_dragon.addEffect("slow_falling", 20, {amplifier: 1, showParticles: false});
                    } else {
                        wind_dragon.setDynamicProperty("pu_biomes_has_rider", false);
                    }
                }
            }
        }
    }
    if (event.id === "pu_biomes:unicorn_signal") {
        const unicorn = event.sourceEntity;
        const rideableComponent = unicorn.getComponent("minecraft:rideable");
        if (rideableComponent) {
            const riders = rideableComponent.getRiders();
            if (riders.length > 0) {
                unicorn.setDynamicProperty("pu_biomes_has_rider", true);
                const rider = riders[0];
                if (rider.isValid()) {
                    unicorn.addEffect("speed", 10, {amplifier: 2, showParticles: false});

                    if(rider.isJumping) {
                        rider.setDynamicProperty("pu_biomes_unicorn_jump", true);
                    }
                    
                    if (!rider.isJumping && rider.getDynamicProperty("pu_biomes_unicorn_jump")) {
                        rider.playAnimation("animation.pu_biomes.unicorn.alarm");
                        rider.setDynamicProperty("pu_biomes_unicorn_jump", false);
                    }
                }
            }
        }
    }
    if (event.id === "pu_biomes:woodpecker_signal") {
        const woodpecker = event.sourceEntity;
    
        const directions = [
            { x: 1, z: 0, rotation: 270 },  // East
            { x: -1, z: 0, rotation: 90 }, // West
            { x: 0, z: 1, rotation: 0 }, // South
            { x: 0, z: -1, rotation: 180 }   // North
        ];
    
        const woodpeckerLoc = woodpecker.location;
    
        for (const dir of directions) {
            const checkX = Math.floor(woodpeckerLoc.x + dir.x);
            const checkY = Math.floor(woodpeckerLoc.y);
            const checkZ = Math.floor(woodpeckerLoc.z + dir.z);
    
            const block = woodpecker.dimension.getBlock({ x: checkX, y: checkY, z: checkZ });
    
            if (block && WOOD_BLOCKS.includes(block.typeId)) {
                woodpecker.setRotation({ x: 0, y: dir.rotation });
                break;
            }
        }
    }
    if (event.id === "pu_biomes:fire_spirit_combat") {
        const fire_spirit = event.sourceEntity;
        if (!fire_spirit.isValid()) return;
        try {
            const fire_spiritLoc = fire_spirit.location;
            const block = fire_spirit.dimension.getBlock(fire_spiritLoc);
            if (block && block.typeId === "minecraft:air") {
                block.setPermutation(BlockPermutation.resolve("minecraft:fire"));
            }
        } catch (error) {
        }
    }
    if (event.id === "pu_biomes:toxic_cloud") {
        const toxic_slime = event.sourceEntity;
        if (!toxic_slime.isValid()) return;
        try {
            const toxic_slimeLoc = toxic_slime.location;
            const dimension = toxic_slime.dimension;
            dimension.spawnParticle('pu_biomes:toxic_cloud_1', toxic_slimeLoc);
            dimension.spawnParticle('pu_biomes:toxic_cloud_2', toxic_slimeLoc);
            dimension.playSound("pu_biomes:slime_loop", toxic_slimeLoc);
            const entities = dimension.getEntities({
                location: toxic_slimeLoc,
                maxDistance: 3
            });
            entities.forEach(e => {
                if(e.typeId !== 'minecraft:item') {
                    e?.addEffect('poison', 5 * 20, { amplifier: 1 });
                    e?.applyDamage(5);
                }
            });
        } catch (error) {
        }
    }

    if (event.id === "pu_biomes:firefly_bottle") {
        const firefly_bottle = event.sourceEntity;
        if (!firefly_bottle.isValid()) return;
    
        try {
            const firefly_bottleLoc = firefly_bottle.location;
            const dimension = firefly_bottle.dimension;
            
            // Particle effect
            dimension.spawnParticle('pu_biomes:firefly_splash', firefly_bottleLoc);
            firefly_bottle.remove();
            
            // Nearby air blocks (random 1–2)
            const offsets = [
                {x: 0, y: 1, z: 0},
                {x: 1, y: 1, z: 0},
                {x: -1, y: 1, z: 0},
                {x: 0, y: 1, z: 1},
                {x: 0, y: 1, z: -1}
            ];
            const shuffled = offsets.sort(() => 0.5 - Math.random()).slice(0, Math.floor(Math.random() * 2) + 1);
            
            for (const offset of shuffled) {
                const pos = {
                    x: Math.floor(firefly_bottleLoc.x + offset.x),
                    y: Math.floor(firefly_bottleLoc.y + offset.y),
                    z: Math.floor(firefly_bottleLoc.z + offset.z)
                };
                
                const block = dimension.getBlock(pos);
                if (block.typeId === "minecraft:air") {
                    animateLightBlock(dimension, pos);
                }
            }
        } catch (error) {
        }
    }
    
    if (event.id === "pu_biomes:islander_signal") {
        const islander = event.sourceEntity;
        if (!islander?.isValid()) return;

        // If this islander is on cooldown, skip it
        if (islander.getDynamicProperty("pu_biomes_islander_cooldown")) return;

        const nearbyEntities = islander.dimension.getEntities({
            location: islander.location,
            maxDistance: 32,
        });

        // Count nearby islanders (not on cooldown)
        const islandersNearby = nearbyEntities.filter(e =>
            e.typeId === 'pu_biomes:islander' &&
            !e.getDynamicProperty("pu_biomes_islander_cooldown")
        );

        // Check for any nearby cloud monsters
        const cloudMonstersNearby = nearbyEntities.some(e =>
            e.typeId === 'pu_biomes:cloud_monster'
        );

        if (islandersNearby.length === 4 && !cloudMonstersNearby) {
            // Spawn the cloud monster in the center of the islanders
            const avgX = islandersNearby.reduce((sum, e) => sum + e.location.x, 0) / 4;
            const avgY = islandersNearby.reduce((sum, e) => sum + e.location.y, 0) / 4;
            const avgZ = islandersNearby.reduce((sum, e) => sum + e.location.z, 0) / 4;

            islander.dimension.spawnEntity("pu_biomes:cloud_monster", { x: avgX, y: avgY, z: avgZ });

            // Put all 4 islanders on cooldown
            islandersNearby.forEach(e => {
                e.setDynamicProperty("pu_biomes_islander_cooldown", true);
                system.runTimeout(() => {
                    if (e.isValid()) {
                        e.setDynamicProperty("pu_biomes_islander_cooldown", false);
                    }
                }, 20 * 250); // 30 seconds
            });
        }
    }

    
});

// Animate your custom light blocks: light_block_1 → light_block_15 → back to air
function animateLightBlock(dimension, pos) {
    // Light on: fast ramp-up
    for (let level = 1; level <= 15; level++) {
        system.runTimeout(() => {
            dimension.runCommandAsync(`setblock ${pos.x} ${pos.y} ${pos.z} light_block_${level}`);
        }, level * 2); // 2 ticks per level
    }

    // Light off: slower fade-down
    for (let level = 14; level >= 0; level--) {
        system.runTimeout(() => {
            if (level === 0) {
                dimension.runCommandAsync(`setblock ${pos.x} ${pos.y} ${pos.z} air`);
            } else {
                dimension.runCommandAsync(`setblock ${pos.x} ${pos.y} ${pos.z} light_block_${level}`);
            }
        }, 90 + (15 - level) * 6); // starts after 30 ticks, 6 ticks per step
    }
}