local Player = {}

local function clamp(value, minimum, maximum)
  return math.max(minimum, math.min(maximum, value))
end

function Player.new()
  return {
    x = love.graphics.getWidth() / 2,
    y = love.graphics.getHeight() * 0.72,
    radius = 14,
    speed = 260,
    invulnerable = 0,
  }
end

function Player.update(player, dt)
  local dx, dy = 0, 0

  if love.keyboard.isDown("left", "a") then dx = dx - 1 end
  if love.keyboard.isDown("right", "d") then dx = dx + 1 end
  if love.keyboard.isDown("up", "w") then dy = dy - 1 end
  if love.keyboard.isDown("down", "s") then dy = dy + 1 end

  local length = math.sqrt(dx * dx + dy * dy)
  if length > 0 then
    dx, dy = dx / length, dy / length
  end

  player.x = clamp(
    player.x + dx * player.speed * dt,
    player.radius,
    love.graphics.getWidth() - player.radius
  )
  player.y = clamp(
    player.y + dy * player.speed * dt,
    player.radius,
    love.graphics.getHeight() - player.radius
  )
  player.invulnerable = math.max(0, player.invulnerable - dt)
end

function Player.draw(player)
  if player.invulnerable > 0 and math.floor(player.invulnerable * 12) % 2 == 0 then
    return
  end

  love.graphics.setColor(0.33, 0.91, 0.84)
  love.graphics.circle("fill", player.x, player.y, player.radius)
  love.graphics.setColor(0.06, 0.12, 0.18)
  love.graphics.circle("fill", player.x + 4, player.y - 3, 3)
  love.graphics.setColor(1, 1, 1, 0.65)
  love.graphics.circle("line", player.x, player.y, player.radius + 4)
end

return Player
