const spinSpeed = 30
var spinFactor = 3

var pfp

var music

if (teto) {
    music = new Audio("/snds/Triple Baka.ogg")
    music.volume = 0.5
} else {
    music = new Audio("/snds/Lotus Waters.ogg")
}

music.loop = true
music.preservesPitch = false

var spins = 0
var lastSent = 0
var globalSpins = 0

var spinning = false

var spinWaiting = false

function resetPFP() {
    $(".pfp")
}

function lerp(a, b, t) {
    return a * (1 - t) + b * t
}

function spinLoop() {
    spinWaiting = true
    setTimeout(() => {
        spinWaiting = false
        if (spinning) {
            // music.volume = 0.5
            if (music.currentTime > 6.5 && teto) {
                spinFactor = 0.25
            } else {
                spinFactor = 3
            }
            if (!teto) {
                music.playbackRate = lerp(music.playbackRate, 1, 1/spinSpeed)
                music.volume = lerp(music.volume, 0.5, 1/spinSpeed)
            }
            spins += 1/spinSpeed / spinFactor
            if (Math.floor(spins) != lastSent && sock && sock.OPEN) {
                $(".globalSpins").text(globalSpins + 1)
                lastSent = Math.floor(spins)
                // resetPFP()
                sock.send(`{"op": 4}`)
                if (spins > 1) {
                    $(".spinnyCount").css("display", "block")
                    $(".localSpins").html(lastSent);
                }
            }
        } else {
            if (!teto) {
                music.playbackRate = lerp(music.playbackRate, 0.5, 1/spinSpeed)
                music.volume = lerp(music.volume, -0, 3/spinSpeed)
            } else {
                music.pause()
                music.currentTime = 1.5
            }

            spins = lerp(spins, Math.round(spins), 1 / spinSpeed * 3)
        }
        $(".pfp").css("rotate", (spins * 360) + "deg")
        spinLoop()
    }, 1/spinSpeed * 1000);
}

document.addEventListener("DOMContentLoaded", function() {
    $("#jsEnabled").text("true")

    pfp = $(".pfp")

    spinLoop()

    pfp.on("mousedown", () => {
        // if (!spinWaiting) {
        //     spinLoop();
        // }
        music.play()

        spinning = true
    })

    document.body.onmouseup = () => {
        if (music.currentTime != 0) {
            // music.currentTime = 0
            // music.pause()

            // whipLash.currentTime = 0
            // whipLash.play()

            spinning = false
        }
    }
})