const clamp = function(val, min, max) { return Math.min(Math.max(min, val), max) }

var thirdperson_cache = UI.GetValue("Visuals", "WORLD", "View", "Thirdperson")
var person = 0, turned = 1

const thirdperson = function() {
    local = Entity.GetLocalPlayer()
    var thirdperson_cache = UI.GetValue("Thirdperson distance"),
    hotkey_state = UI.IsHotkeyActive("Script items", "Animated thirdperson"),
    fade_factor = ((1 / .005) * Globals.Frametime())
    if(hotkey_state && person != 1 && Entity.IsAlive(local))
        person = clamp(person - fade_factor, 49, thirdperson_cache)
    if(!hotkey_state && person != 0 || !Entity.IsAlive(local))
        person = clamp(person + fade_factor, 49, thirdperson_cache)
    if(hotkey_state && person == 49 && turned) {
        UI.ToggleHotkey("Visuals", "WORLD", "View", "Thirdperson")
        turned = 0
    }

    if(!hotkey_state && person > 49 && !turned) {
        UI.ToggleHotkey("Visuals", "WORLD", "View", "Thirdperson")
        turned = 1
    }

    if(turned && !UI.IsHotkeyActive("Visuals", "WORLD", "View", "Thirdperson") || !turned && UI.IsHotkeyActive("Visuals", "WORLD", "View", "Thirdperson"))
        UI.ToggleHotkey("Visuals", "WORLD", "View", "Thirdperson")
    if(person != 0) UI.SetValue("Visuals", "WORLD", "View", "Thirdperson", person );
}

UI.AddHotkey("Animated thirdperson")
UI.AddSliderInt("Thirdperson distance", 50, 250)

const unload = function() {
    UI.SetValue("Visuals", "WORLD", "View", "Thirdperson", thirdperson_cache );
}

Cheat.RegisterCallback("FrameStageNotify", "thirdperson");
Cheat.RegisterCallback("Unload", "unload");