local coroutineEntity = monocle.Entity()

local vector2 = require("#microsoft.xna.framework.vector2")

local badeline = nil

local function badeline_appears(right_side)
  -- determine the position and flipping properties
  local pos_x, scale
  if right_side then
    pos_x = player.Position.X - 18
    scale = 1
  else
    pos_x = player.Position.X + 38
    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.X = scale
  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()
  log("0")
  -- tell the badeline entity to disappear
  badeline:Vanish()
  log("1")
  -- clear the stored variable so the memory can be used for something else
  log("2")
  badeline = nil

  -- wait until the next frame
  log("3")
  wait()
end

function onBegin(room)
  disableMovement()
  badeline_appears()
  coroutine.yield(getLevel():ZoomTo(vector2(140, 80), 1.15, 2.5))
  say("donk_LuxarisEndingA")
  player.ForceCameraUpdate = false
  walk(8, false, 0.8)
  getLevel():add(coroutineEntity)
  coroutineEntity:add(monocle.Coroutine(badeline:FloatTo(vector2(541, 1884), -1, true)))
  coroutineEntity:add(monocle.Coroutine(walk(20, false, 2)))
  player.DummyAutoAnimate = false
  player.Sprite:Play("sitDown", false)
  wait(1)
  say("donk_LuxarisEndingB")
  wait(2)
  say("donk_LuxarisEndingC")
  coroutine.yield(engine.Scene:ZoomBack(4))
  player.ForceCameraUpdate = false
  wait(1.5)
  coroutine.yield(celeste.CutsceneEntity.CameraTo(vector2(player.Position.X, player.Position.Y - 1120), 5, monocle.Ease.SineInOut))
  wait(1)
  setFlag("luxaris_TheEnd", True)
  wait(2)
  setFlag("luxaris_TheEnd2", True)
  wait(3)
  setFlag("SlowFadeToBlack_Luxa", True)
  wait(3)
  completeArea(True, False, True)
end

function onEnd(room, wasSkipped)
  if badeline then
    badeline:RemoveSelf()
    badeline = nil
  end
  player.ForceCameraUpdate = true
  enableMovement()
  completeArea(True, False, True)
end