var speedMilestones = [
    500,  // 2
    1000, // 3
    1500, // 4
    2000, // 5
    2500, // 6
    3000, // 7
    3500, // 8
    4000, // 9
]

StartupEvents.registry('palladium:abilities', (event) => {
    event.create('arrzenhanced:level_tracker')
    .icon(palladium.createItemIcon('minecraft:compass'))
    .tick((entity, entry, holder, enabled) => global.levelTracker(entity, entry, holder, enabled));
});

global.levelTracker = (entity, entry, holder, enabled) => {
    if (enabled) {
        var speedMax = palladium.getProperty(entity, 'arrzenhanced.maxSpeed')
        var tachBoost = palladium.getProperty(entity, 'arrzenhanced.tachyonBoost')
        var realSpeed = speedMax - tachBoost;
        if (realSpeed >= 9) {return}

        var currentExp = palladium.getProperty(entity, 'arrzenhanced.speedExp')
        if (entity.onGround()) {
            if (!entity.persistentData['lastPos']) {
                entity.persistentData['lastPos'] = {}
                entity.persistentData['lastPos'].x = Math.round(entity.getX())
                entity.persistentData['lastPos'].z = Math.round(entity.getZ())
            } else {
                if (
                    entity.persistentData['lastPos'].x != Math.round(entity.getX()) ||
                    entity.persistentData['lastPos'].z != Math.round(entity.getZ())
                ) {
                    currentExp += 1;
                }
                entity.persistentData['lastPos'].x = Math.round(entity.getX())
                entity.persistentData['lastPos'].z = Math.round(entity.getZ())
            }
        }
        // if (speedMilestones.includes(currentExp)) {
        if (currentExp % 500 == 0) {
            var speedMax = palladium.getProperty(entity, 'arrzenhanced.maxSpeed')
            if (realSpeed+1 > 9) {return;}
            palladium.setProperty(entity, 'arrzenhanced.maxSpeed', speedMax+1)
            var afterLevel = realSpeed+1;
            var beforeLevel = realSpeed;
            entity.getServer().runCommandSilent(`playsound minecraft:entity.player.levelup player @a ${Math.round(entity.getX())} ${Math.round(entity.getY())} ${Math.round(entity.getZ())} 2 1`)
            entity.getServer().runCommandSilent(`title ${entity.name.getString()} title {"text":"Level up!","bold":true,"color":"gold"}`)
            entity.getServer().runCommandSilent(`title ${entity.name.getString()} subtitle ["",{"text":"LV","color":"yellow"},{"text":" ${beforeLevel}","color":"green"},{"text":" >>","bold":true,"color":"dark_green"},{"text":" ${afterLevel}","color":"green"}]`)
            currentExp += 1;
        }

        palladium.setProperty(entity, 'arrzenhanced.speedExp', currentExp);
    };
}