animationTimer = 0
frameDuration = G.animationSpeed or 0.15
currentFrame = 1
elapsedTime = 0
isAnimating = false
tickerInCombat = nil
PedroPositioningMode = false
isFadingOut = false

function StartAnimation(songLength)
    if not songLength or songLength <= 0 then
        songLength = 10
	end
	
	if isAnimating then
		PedroAnimationFrame:SetScript("OnUpdate", nil)
		isAnimating = false
		isFadingOut = false
	end
	
	
    isAnimating = true
    isFadingOut = false
    PedroAnimationFrame:SetAlpha(1)
	
    if PedroAnimationFrame.closeBtn then
        PedroAnimationFrame.closeBtn:Hide()
	end
	
    animationTimer = 0
    elapsedTime = 0
    currentFrame = 1
	
    frameDuration = G.animationSpeed or 0.15
	
    local cellSize = 193
    local iconSize = 193
	
    local numCols = 4
    local numRows = 8
	
    local totalWidth  = 1024
    local totalHeight = 2048
	
    PedroAnimationFrame:SetSize(iconSize, iconSize)
	
    PedroAnimationFrame:SetScript("OnUpdate", function(self, elapsed)
        if elapsed > 0.05 then
            elapsed = 0.05
		end
		
        animationTimer = animationTimer + elapsed
        elapsedTime = elapsedTime + elapsed
		
        if not isFadingOut and elapsedTime >= frameDuration then
            elapsedTime = elapsedTime - frameDuration
            currentFrame = currentFrame + 1
			
            if currentFrame > (numCols * numRows) then
                currentFrame = 1
			end
			
            local col = (currentFrame - 1) % numCols
            local row = math.floor((currentFrame - 1) / numCols)
			
            local left_px   = col * cellSize
            local right_px  = left_px + cellSize
            local top_px    = row * cellSize
            local bottom_px = top_px + cellSize
			
            local left   = left_px / totalWidth
            local right  = right_px / totalWidth
            local top    = top_px / totalHeight
            local bottom = bottom_px / totalHeight
			
            PedroAnimationTexture:SetTexCoord(left, right, top, bottom)
		end
		
        if not isFadingOut and animationTimer >= songLength then
            isFadingOut = true
            self.fadeStart = GetTime()
		end
		
        if isFadingOut then
            local fadeDuration = 0.25
            local progress = (GetTime() - self.fadeStart) / fadeDuration
			
            if progress >= 1 then
                PedroAnimationFrame:SetAlpha(0)
                PedroAnimationFrame:EnableMouse(false)
                if PedroAnimationFrame.closeBtn then
                    PedroAnimationFrame.closeBtn:EnableMouse(false)
				end
                isAnimating = false
                isFadingOut = false
                PedroAnimationFrame:SetScript("OnUpdate", nil)
                return
				else
                PedroAnimationFrame:SetAlpha(1 - progress)
			end
		end
	end)
end
