local monocle = require("#monocle")
local lua_helper = celeste.Mod.LuaCutscenes.LuaHelper
local bettertext = require("#Celeste.Mod.CrossoverCollab.Code.PointsStuff.BetterTextbox")

math.randomseed(os.time())

function bettersay(dialog)
    coroutine.yield(bettertext.Say(tostring(dialog)))
end

local function makeCoroutine(func)
	return monocle.Coroutine(lua_helper.LuaCoroutineToIEnumerator(coroutine.create(func)))
end

wordList = {"At The Speed Of Light", "Crystal Gravity", "LeaF", "MemoryUnlocked", "Chill Night Of Impossible Desires"}

function getRandomWord()
	local index = math.random(#wordList)
	return wordList[index]
end

function moveMenuRoutine()
	while true do
	
		if (celeste.Input.MenuRight.Pressed) then
			playSound("event:/game/general/assist_nonsolid_out")
				teleportTo(164,-16,"menu1","Transition")
		end
	
		if (celeste.Input.MenuLeft.Pressed) then
			playSound("event:/game/general/assist_nonsolid_out")
			teleportTo(164,-16,"menu4","Transition")
		end
		wait()
	end
end

function onBegin()
	cutsceneEntity:Add(makeCoroutine(moveMenuRoutine))
	player.Facing = getEnum("Celeste.Facings", "Right")
	setPlayerState(0, false)
	setFlag("endSong",false)
	local timesTalked = 0
	local totalCoins = 0
	-- Count coins collected across all levels
	for i = 1, 3 do
		for j = 1, 6 do
			if getFlag("song" .. tostring(j) .. "coin" .. tostring(i)) then
				totalCoins = totalCoins + 1
			end
		end
	end
	-- Check if coins have been spent and adjust the counter accordingly
	if getFlag("coinsSpent") then
		totalCoins = totalCoins - 15
	end
	-- Set the counter in the session
	engine.Scene.Session:SetCounter("TotalCoins", totalCoins)

	
	while (celeste.Input.Jump.Pressed or celeste.Input.DashPressed or celeste.Input.CrouchDashPressed or celeste.Input.MenuRight.Pressed or celeste.Input.MenuLeft.Pressed or celeste.Input.MenuConfirm.Pressed) do
		wait(0.05)
	end
	while true do
		if (celeste.Input.Jump.Pressed or celeste.Input.DashPressed or celeste.Input.CrouchDashPressed or celeste.Input.MenuConfirm.Pressed) then
			timesTalked = timesTalked + 1
			playSound("event:/eva/error")
			setFlag("menu6_interacting",true)
			wait(0.04)
			setFlag("menu6_interacting",false)
			if not getFlag("LockTalkedOnce") then
				say("CC_GeometryDash_LockedSong")
				setFlag("LockTalkedOnce",true)
			else
				if timesTalked == 10 then
					bettersay("{anchor bottom}What do you want now? A free achievement? ... Okay.")
					setFlag("talked20Times",true)
				else
					randomDialog = math.random(1,21)
					for i=1,20,1 do
						if randomDialog == i then
							say("CC_GeometryDash_LockedSong"..tostring(i))
						end
						i = i + 1
					end
					if randomDialog == 21 then
						bettersay("{anchor bottom}Don't tell anyone, but I ate the song {~}{#F94A4A}"..getRandomWord().."{#}{/~}, so no one can play it now.")
					end
				end
			end
		end
		wait()
	end
end