import { world, system } from "@minecraft/server";

const vehicleTypes = [
  "pb_dino:boat",
  "pb_dino:jeep",
  "pb_dino:helicopter",
  "pb_dino:plane",
];

// Keep track of the players whose camera has been cleared
const cameraClearedPlayers = new Set();

system.runInterval(() => {
  for (const player of world.getPlayers()) {
    // Check if the player is riding a vehicle
    const getRide = player.getComponent("minecraft:riding")?.entityRidingOn;
    const hasFuel = getRide?.getProperty("pb_dino:has_fuel");
    const driver = getRide?.getComponent("minecraft:rideable").getRiders()[0];

    if (!getRide || !hasFuel) {
      if (getRide?.typeId === "pb_dino:plane" && !getRide.isOnGround) {
        return;
      } else {
        // If not riding, check if the camera has been cleared
        if (!cameraClearedPlayers.has(player)) {
          // Clear the camera and mark the player
          player.camera.clear();
          cameraClearedPlayers.add(player);
        }
        player.removeTag("pb_dino_vehicle_camera");
      }
    } else {
      // If the player is riding a vehicle and it's of the correct type
      if (
        vehicleTypes.includes(getRide.typeId) &&
        hasFuel &&
        driver == player
      ) {
        player.addTag("pb_dino_vehicle_camera");
        // Remove from the cleared set if they are riding a vehicle
        cameraClearedPlayers.delete(player);
      }
    }
  }
});
