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

const CARNAKYLOS_ID = "cyd_dino:carnankylos"
const WHIRLWIND_DAMAGE = 2
const WHIRLWIND_RADIUS = 6

const HORN_ATTACK_RADIUS = 12

system.runInterval(() => {
    for (const boss of world.getDimension("overworld").getEntities({ type: CARNAKYLOS_ID })) {
        if (boss.getComponent("minecraft:variant") && boss.getComponent("minecraft:variant").value === 1) handleCarnakylosWhirlwind(boss)
    }

    for (const boss of world.getDimension("overworld").getEntities({ type: 'cyd_dino:mega' })) {
        if (boss.getComponent("minecraft:variant") && boss.getComponent("minecraft:variant").value === 1) handleMegastyracodonHorn(boss)
    }
}, 10);

function handleCarnakylosWhirlwind(boss) {
    const nearbyEnemies = {
        location: boss.location,
        maxDistance: WHIRLWIND_RADIUS,
        excludeFamilies: ["carnankylos"]
    }

    for (const enemy of boss.dimension.getEntities(nearbyEnemies)) {
        if (!enemy) continue
        enemy.applyDamage(WHIRLWIND_DAMAGE, {
            cause: EntityDamageCause.entityAttack,
            damagingEntity: boss
        })

        try {
            enemy.addEffect("slowness", 20, { amplifier: 0 })
            const direction = {
                x: enemy.location.x - boss.location.x, y: 0.1, z: enemy.location.z - boss.location.z
            }
            enemy.applyKnockback(direction.x, direction.z, 0.8, 0.4)
        } catch ($) { }
    }
}

function handleMegastyracodonHorn(boss) {
    const lastAttackTick = boss.getDynamicProperty("cyd_dino_lastHornAttackTick") ?? 0
    const cooldownTick = 26

    if (system.currentTick - lastAttackTick < cooldownTick) return

    boss.setDynamicProperty("cyd_dino_lastHornAttackTick", system.currentTick)

    const nearbyEnemiesQuery = {
        location: boss.location,
        maxDistance: HORN_ATTACK_RADIUS,
        excludeFamilies: ["megastyracodon"]
    }

    for (const enemy of boss.dimension.getEntities(nearbyEnemiesQuery)) {
        if (!enemy) continue
        enemy.applyDamage(15, { cause: EntityDamageCause.entityAttack, damagingEntity: boss });

        try {
            const direction = {
                x: enemy.location.x - boss.location.x, y: 0.8, z: enemy.location.z - boss.location.z
            }
            enemy.applyKnockback(direction.x, direction.z, 0.5, 0.7);
        } catch ($) { }
    }
}