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

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

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

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

		wait()
	end
end

function onBegin()
	cutsceneEntity:Add(makeCoroutine(moveMenuRoutine))
	player.Facing = getEnum("Celeste.Facings", "Right")
	setPlayerState(0, false)
	setFlag("endSong",false)
	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
			playSound("event:/CrossoverCollab/Xelk1/SFX/LevelSelected")
			teleportTo(16,664,"song3","Transition")
		end
		wait()
	end
end