// main.js
var draw = use('draw2d')
var config = use('config')
var color = use('color')
var random = use('random')

prosperon.camera.transform.pos = [0,0]

var paddleW = 10, paddleH = 80
var p1 = {x: 30, y: config.height*0.5, speed: 300}
var p2 = {x: config.width-30, y: config.height*0.5, speed: 300}
var ball = {x: 0, y: 0, vx: 220, vy: 150, size: 10}
var score1 = 0, score2 = 0

function resetBall() {
  ball.x = config.width*0.5
  ball.y = config.height*0.5
  // give it a random vertical bounce
  ball.vy = (random.random()<0.5 ? -1:1)*150
  // keep horizontal speed to the same magnitude
  ball.vx = ball.vx>0 ? 220 : -220
}

resetBall()

var update = function(dt) {
  // Move paddles: positive Y is up, so W/↑ means p.y += speed
  if (input.keyboard.down('w')) p1.y += p1.speed*dt
  if (input.keyboard.down('s')) p1.y -= p1.speed*dt

  // Paddle 2 movement (ArrowUp = up, ArrowDown = down)
  if (input.keyboard.down('i')) p2.y += p2.speed*dt
  if (input.keyboard.down('k')) p2.y -= p2.speed*dt

  // Clamp paddles to screen
  if (p1.y < paddleH*0.5) p1.y = paddleH*0.5
  if (p1.y > config.height - paddleH*0.5) p1.y = config.height - paddleH*0.5
  if (p2.y < paddleH*0.5) p2.y = paddleH*0.5
  if (p2.y > config.height - paddleH*0.5) p2.y = config.height - paddleH*0.5

  // Move ball
  ball.x += ball.vx*dt
  ball.y += ball.vy*dt

  // Bounce top/bottom
  if (ball.y+ball.size*0.5>config.height || ball.y-ball.size*0.5<0) ball.vy = -ball.vy

  // Check paddle collisions
  // p1 bounding box
  var left1 = p1.x - paddleW*0.5, right1 = p1.x + paddleW*0.5
  var top1 = p1.y + paddleH*0.5, bottom1 = p1.y - paddleH*0.5
  // p2 bounding box
  var left2 = p2.x - paddleW*0.5, right2 = p2.x + paddleW*0.5
  var top2 = p2.y + paddleH*0.5, bottom2 = p2.y - paddleH*0.5

  // ball half-edges
  var l = ball.x - ball.size*0.5, r = ball.x + ball.size*0.5
  var b = ball.y - ball.size*0.5, t = ball.y + ball.size*0.5

  // Collide with paddle 1?
  if (r>left1 && l<right1 && t>bottom1 && b<top1)
    ball.vx = abs(ball.vx)
  // Collide with paddle 2?
  if (r>left2 && l<right2 && t>bottom2 && b<top2)
    ball.vx = -abs(ball.vx)

  // Check left/right out-of-bounds
  if (r<0) { score2++; resetBall() }
  if (l>config.width) { score1++; resetBall() }
}

var hud = function() {
  // Clear screen black
  draw.rectangle({x:0, y:0, width:config.width, height:config.height}, [0,0,0,1])

  // Draw paddles
  draw.rectangle({x:p1.x - paddleW*0.5, y:p1.y - paddleH*0.5, width:paddleW, height:paddleH}, color.white)
  draw.rectangle({x:p2.x - paddleW*0.5, y:p2.y - paddleH*0.5, width:paddleW, height:paddleH}, color.white)

  // Draw ball
  draw.rectangle({x:ball.x - ball.size*0.5, y:ball.y - ball.size*0.5, width:ball.size, height:ball.size}, color.white)

  // Simple score display
  var msg = score1 + "   " + score2
  draw.text(msg, {x:0, y:10, width:config.width, height:40}, null, 0, color.white, 0)
}
