local switched = false
local fadeTimer = 0
local FADE_DURATION = 1*MUSICRATE

local MESSAGE = "1 minute remaining!"
local MESSAGE_DURATION = 105

local TARGET_Y = BASEVIDHEIGHT - 75
local messageTimer = {}
local triggered = {}
local lastTimelimit = 0

local cv_showdownsequence = CV_RegisterVar({
    name = "an_showdown",
    defaultvalue = "On",
    flags = CV_NETVAR,
    PossibleValue = CV_OnOff
})

addHook("PlayerThink", function(player)
	if gamemap ~= 123 then return end
	if cv_showdownsequence.value == 0 then return end
    if timelimit == 0 then return end
	if timelimit == 1 then return end
	
	--Constantly poll for any timelimit changes and reset accordingly
    if timelimit ~= lastTimelimit then
        lastTimelimit = timelimit
        switched = false
        triggered = {}
        fadeTimer = 0
    end
	
	if messageTimer[player] == nil then messageTimer[player] = 0 end
    if triggered[player] == nil then triggered[player] = false end

	if messageTimer[player] > 0 then
        messageTimer[player] = messageTimer[player] - 1
    end
	
	local totalTics = timelimit*60*TICRATE
	local timeLeft = totalTics - leveltime
	
	if timeLeft <= 61*TICRATE and not triggered[player] then
        triggered[player] = true
        messageTimer[player] = MESSAGE_DURATION
		P_FlashPal(player, PAL_WHITE, 10)
    end
	
	--Music fade begins
	if player == consoleplayer then
		if timeLeft <= 62*TICRATE and not switched then
			switched = true
			fadeTimer = TICRATE
			S_FadeOutStopMusic(FADE_DURATION)
		end
	
		--Switch music after fade completes using tunes instead of S_ChangeMusic
		if fadeTimer > 0 then
			fadeTimer = fadeTimer - 1
			if fadeTimer == 0 then
				COM_BufInsertText(consoleplayer, "tunes SHWD")
			end
		end
	end
end)

addHook("HUD", function(v, player)
	if gamemap ~= 123 then return end
	if not player or player.spectator then return end
	
    if messageTimer[player] and messageTimer[player] > 0 then
        local t = messageTimer[player]

        local alpha
        if t > 80 then
            alpha = 0
        elseif t > 60 then
            alpha = V_20TRANS
        elseif t > 40 then
            alpha = V_40TRANS
        elseif t > 20 then
            alpha = V_60TRANS
        else
            alpha = V_80TRANS
        end

        v.drawString(
            BASEVIDWIDTH / 2,
            TARGET_Y,
            MESSAGE,
            V_ALLOWLOWERCASE | alpha,
            "center"
        )
    end
end, "game")

--Reset when a new map starts
addHook("MapLoad", function()
	triggered = {}
	messageTimer = {}
    switched = false
	fadeTimer = 0
	lastTimelimit = timelimit
end)