import { updatePlayerPosition, createPlayer } from './player.js';
import { initPlatforms, moveWorld } from './platforms.js';
import { GAME_COLORS, PLATFORMS_GAP } from './constants.js';

// Game state
let player;
let platforms;
let pendingWorldMove = 0;
let gameOver = false;

export function getScore() {
  return (player?.elevation ?? 0) / PLATFORMS_GAP * 10;
}

export function isGameOver() {
  return gameOver;
}

export function resetGame() {
  allSprites.remove();
  pendingWorldMove = 0;
  gameOver = false;
  platforms = initPlatforms();
  player = createPlayer();
}

export function initializeGame() {
  world.gravity.y = 10;
  resetGame();
}

export function updateGame() {
  clear();
  background(GAME_COLORS.background);

  if (gameOver) {
    return;
  }

  pendingWorldMove += updatePlayerPosition(player, platforms);
  player.rotation = player.vel.x * 1.5;

  if (pendingWorldMove > PLATFORMS_GAP) {
    const move = Math.min(pendingWorldMove, 5);
    pendingWorldMove -= move;
    platforms = moveWorld(platforms, player.elevation, move);
    player.y += move;
    player.bounciness = 0;
  }

  if (player.y > height) {
    gameOver = true;
  }

  fill(0);
  textSize(40);
  textAlign(RIGHT);
  text(getScore(), width - 20, 50);
}
