var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var joystick = {
  x: canvas.width / 2,
  y: canvas.height / 2,
  radius: 50,
  isPressed: false
};

var car = {
  isMoving: false,
  moveDirection: ""
};

function drawJoystick() {
  // Clear the canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Draw the joystick
  ctx.beginPath();
  ctx.arc(joystick.x, joystick.y, joystick.radius, 0, Math.PI * 2);
  ctx.strokeStyle = "#333";
  ctx.lineWidth = 6;
  ctx.stroke();

  // Draw the joystick handle
  ctx.beginPath();
  ctx.arc(joystick.x, joystick.y, joystick.radius * 0.5, 0, Math.PI * 2);
  ctx.fillStyle = "#333";
  ctx.fill();
}

function handleTouchStart(event) {
  joystick.isPressed = true;
  handleTouchMove(event);
}

function handleTouchEnd(event) {
  joystick.isPressed = false;
  joystick.x = canvas.width / 2;
  joystick.y = canvas.height / 2;
  drawJoystick();
  if (car.isMoving) {
    car.isMoving = false;
    Manual.stop();
  }
}

function handleTouchMove(event) {
  if (joystick.isPressed) {
    joystick.x = event.touches[0].clientX - canvas.offsetLeft;
    joystick.y = event.touches[0].clientY - canvas.offsetTop;
    drawJoystick();

    // Determine the direction of movement based on the joystick angle
    var dx = joystick.x - (canvas.width / 2);
    var dy = joystick.y - (canvas.height / 2);
    var angle = Math.atan2(dx, dy);
    if (angle < 0) {
      angle += Math.PI * 2;
    }

    var degrees = 90 - angle * 180 / Math.PI;
    if (degrees < 0) {
      degrees += 360;
    }


    if (degrees >= 45 && degrees < 135) {
      // Move up (left arrow)
      if (car.moveDirection !== "down") {
        car.moveDirection = "down";
        Manual.downArrowEvent();
      }
    } else if (degrees >= 135 && degrees < 225) {
      // Move left (down arrow)
      if (car.moveDirection !== "left") {
        car.moveDirection = "left";
        Manual.leftArrowEvent();
      }
    } else if (degrees >= 225 && degrees < 315) {
      // Move down (right arrow)
      if (car.moveDirection !== "up") {
        car.moveDirection = "up";
        Manual.upArrowEvent();
      }
    } else {
      // Move right (up arrow)
      if (car.moveDirection !== "right") {
        car.moveDirection = "right";
        Manual.rightArrowEvent();
      }
    }

    // Start moving the car if it's not already moving
    if (!car.isMoving) {
      car.isMoving = true;
    }
  }
}

canvas.addEventListener("touchstart", handleTouchStart);
canvas.addEventListener("touchend", handleTouchEnd);
canvas.addEventListener("touchmove", handleTouchMove);
