-- store the badeline entity outside the functions, so it can be accessed whenever necessary
local badeline = nil

local function badeline_appears(left_side)
  -- determine the position and flipping properties
  local pos_x, scale
  if left_side then
    pos_x = player.Position.X + 18
    scale = -1
  else
    pos_x = player.Position.X - 18
    scale = 1
  end
  local pos_y = player.Position.Y - 8

  -- create and add a new badeline dummy entity
  badeline = celeste.BadelineDummy(vector2(pos_x, pos_y))
  badeline.Sprite.Scale = vector2(scale, 1.0)
  local returnDepth = badeline.Depth
  badeline.Depth = 1000000
  getLevel():Add(badeline)

  -- play sound + effect
  getLevel().Displacement:AddBurst(badeline.Center, 0.5, 8, 32, 0.5)
  playSound("event:/char/badeline/maddy_split", badeline.Position)

  -- wait until the next frame so all that can take effect properly
  wait()
end

local function badeline_vanishes()
  -- tell the badeline entity to disappear
  badeline:Vanish()
  Input.Rumble(getEnum("Celeste.RumbleStrength", "Medium"), getEnum("Celeste.RumbleLength", "Medium"))
  -- clear the stored variable so the memory can be used for something else
  badeline = nil

  -- wait until the next frame
  wait()
end

function onBegin(room)
  wait(1.0)
  disableMovement()
  wait(0.3)
  getInventory()
  player.Facing = luanet.enum(luanet.import_type("Celeste.Facings"), "Left")
  coroutine.yield(engine.Scene:ZoomTo(vector2(240, 130), 2, 1.2))
  wait(0.2)
  walk(-20)
  wait(0.4)
  badeline_appears()
  wait(0.6)
  say("fifigiftmapcutscene1")
  coroutine.yield(engine.Scene:ZoomAcross(vector2(80, 130), 2, 1.5))
  say("fifigiftmapcutscene2")
  coroutine.yield(engine.Scene:ZoomAcross(vector2(240, 130), 2, 1.5))
  say("fifigiftmapcutscene3")
  walk(20, true)
  coroutine.yield(badeline:FloatTo(vector2(player.Position.X + 1, player.Position.Y - 5), 1.5, false))
  badeline:RemoveSelf()
  engine.Scene.Displacement:AddBurst(player.Position, 0.5, 24, 96, 0.4)
  player:CreateSplitParticles()
  playSound("event:/char/badeline/disappear", badeline.Position)
  setInventory("TheSummit")
  wait(0.2)
  coroutine.yield(engine.Scene:ZoomBack(1.0))
end

function onEnd(room, wasSkipped)
  if badeline then
    badeline:RemoveSelf()
    badeline = nil
  end 
  if wasSkipped then
      instantTeleportTo(-2410, -9848)
      player.Facing = luanet.enum(luanet.import_type("Celeste.Facings"), "Left")
      setInventory("TheSummit")
  end
  enableMovement()
end