<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Simple Vehicle Movement</title>

<link href="https://unpkg.com/maplibre-gl@3.6.2/dist/maplibre-gl.css" rel="stylesheet">

<style>
  html, body {
    margin: 0;
    padding: 0;
    overflow: hidden;
    height: 100%;
  }
  #map {
    position: absolute;
    inset: 0;
  }
  #car {
    position: absolute;
    width: 40px;
    height: 40px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    pointer-events: none;
    z-index: 10;
    background: white;
    border-radius: 6px;
    box-shadow: 0 0 10px rgba(0,255,255,0.8);
  }
</style>
</head>
<body>

<div id="map"></div>
<div id="car"></div>

<script src="https://unpkg.com/maplibre-gl@3.6.2/dist/maplibre-gl.js"></script>

<script>
/* ---------------- BASIC CONFIG ---------------- */
let player = {
  lng: 173.28463,
  lat: -41.27011,
  heading: 0,      // degrees
  speed: 25        // meters per second
};

const keys = { w:false, s:false, a:false, d:false };

const METERS_PER_DEG_LAT = 111320;

/* ---------------- INPUT ---------------- */
window.addEventListener("keydown", e => {
  if (e.key === "w") keys.w = true;
  if (e.key === "s") keys.s = true;
  if (e.key === "a") keys.a = true;
  if (e.key === "d") keys.d = true;
});

window.addEventListener("keyup", e => {
  if (e.key === "w") keys.w = false;
  if (e.key === "s") keys.s = false;
  if (e.key === "a") keys.a = false;
  if (e.key === "d") keys.d = false;
});

/* ---------------- MAP INIT ---------------- */
let map;
let lastTime = performance.now();

window.onload = () => {
  map = new maplibregl.Map({
    container: 'map',
    style: 'https://api.maptiler.com/maps/019d3452-4395-7ecd-bbf0-c64a3d5060cd/style.json?key=uHmPABwBFcVhiPJcdCzb',
    center: [player.lng, player.lat],
    zoom: 19,
    pitch: 45,
    bearing: 0
  });

  map.on("render", gameLoop);
};

/* ---------------- MAIN LOOP ---------------- */
function gameLoop() {
  const now = performance.now();
  const dt = (now - lastTime) / 1000;
  lastTime = now;

  updatePlayer(dt);
  map.setCenter([player.lng, player.lat]);

  // Rotate car icon
  document.getElementById("car").style.transform =
    `translate(-50%, -50%) rotate(${player.heading}deg)`;
}

/* ---------------- VEHICLE MOVEMENT ---------------- */
function updatePlayer(dt) {
  const metersPerDegLng = METERS_PER_DEG_LAT * Math.cos(player.lat * Math.PI/180);

  // Rotate car
  if (keys.a) player.heading -= 120 * dt; // turn left
  if (keys.d) player.heading += 120 * dt; // turn right

  // Move forward/backward in direction car is facing
  let move = 0;
  if (keys.w) move = player.speed * dt;
  if (keys.s) move = -player.speed * dt;

  const rad = player.heading * Math.PI / 180;
  const dx = Math.cos(rad) * move;
  const dy = Math.sin(rad) * move;

  player.lat += dy / METERS_PER_DEG_LAT;
  player.lng += dx / metersPerDegLng;
}
</script>

</body>
</html>
