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

world.afterEvents.entityHurt.subscribe(event => {
    const { damageSource, hurtEntity } = event
    const mantis = damageSource.damagingEntity
    if (!mantis || mantis.typeId != 'ff:mantis' || !hurtEntity || hurtEntity.getComponent('health').currentValue <= 0) return;
    mantis.triggerEvent('add_ridable')
    mantis.addTag(mantis.id.toString())
    hurtEntity.runCommandAsync(`ride @s start_riding @e[c=1,tag="${mantis.id}"] teleport_rider if_group_fits`)
    mantis.addEffect('slowness', 80, { amplifier: 255, showParticles: false })
    system.runTimeout(() => {
        if (hurtEntity.getComponent('riding')?.entityRidingOn?.id != mantis.id) return;
        hurtEntity.applyDamage(13, { cause: EntityDamageCause.entityAttack, damagingEntity: mantis })
    }, 58)
})

world.afterEvents.itemCompleteUse.subscribe(event => {
    const { itemStack, source } = event
    switch (itemStack.typeId) {
        case 'ff:shrimp_cocktail':
            source.addEffect('speed', 600, { amplifier: 1 })
            break;
        case 'ff:raw_crab_claw':
        case 'ff:raw_crab_leg':
            source.addEffect('nausea', 200)
            source.addEffect('poison', 200)
            break;
        case 'ff:crab_burger':
            source.addEffect('water_breathing', 600)
            break;
        default:
            break;
    }
})

system.runInterval(() => {

    const entities = world.getDimension('overworld').getEntities({ type: 'ff:elephant' })

    if (!entities.length > 0) return;

    entities.forEach(entity => {

        const player = entity.getComponent('rideable')?.getRiders()[0]

        if (!player) return;

        const stunned = entity.getComponent('is_stunned')

        if (stunned && !player.isJumping) return;
        else if (stunned && player.isJumping) { player.onScreenDisplay.setActionBar("§c - [ On Cooldown ] -"); return }

        if (!player.isJumping) return;

        if (!entity.getComponent('is_saddled')) return;

        entity.triggerEvent('stomp')

        system.runTimeout(() => {
            entity.dimension.getEntities({ location: entity.location, maxDistance: 5 }).filter(e => e.id != player.id && e.id != entity.id && !e.typeId.includes('item')).forEach(target => {
                const multiplier = Math.sqrt(Math.pow(target.location.x - entity.location.x, 2) + Math.pow(target.location.y - entity.location.y, 2) + Math.pow(target.location.z - entity.location.z, 2)) / 5;
                target.applyDamage(7 * multiplier, { cause: EntityDamageCause.entityAttack, damagingEntity: entity })
                const launchVector = { x: entity.location.x - target.location.x, y: 0, z: entity.location.z - target.location.z }
                target.applyKnockback(-launchVector.x, -launchVector.z, 1 * multiplier, 1)
            })
        }, 0.8333 * 20)

    })

}, 2)