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

let jumpTapCount = 0;
let jumpReleased = true;
let lastJumpPressTime = 0;
let lastJumpReleaseTime = 0;

const maxHoldTime = 500; // Max time a jump press is considered valid
const doubleTapInterval = 300; // Max time between taps for a double-tap

function doubleTapper(player, vehicle) {
  const lightsProperty = vehicle.getProperty("pb_plane:lights");
  if (player.isJumping) {
    // Detect first jump press
    if (jumpReleased) {
      lastJumpPressTime = Date.now();
      jumpReleased = false; // Button is now held
    }

    // Reset tap count if held too long
    if (Date.now() - lastJumpPressTime > maxHoldTime) {
      jumpTapCount = 0;
    }
  } else {
    // Detect jump release
    if (!jumpReleased) {
      jumpReleased = true;
      lastJumpReleaseTime = Date.now();

      // Check if the release is within the double-tap interval
      if (Date.now() - lastJumpPressTime <= maxHoldTime) {
        if (Date.now() - lastJumpReleaseTime <= doubleTapInterval) {
          jumpTapCount++;
        } else {
          jumpTapCount = 1; // Reset count if too much time passed
        }

        // Toggle lights on double-tap
        if (jumpTapCount === 2) {
          jumpTapCount = 0; // Reset counter after toggling
          if (lightsProperty == true) {
            vehicle.setProperty("pb_plane:lights", false);
          } else {
            vehicle.setProperty("pb_plane:lights", true);
          }
        }
      }
    }
  }
}

function getVehicleData(player) {
  const vehicle = player.getComponent("minecraft:riding")?.entityRidingOn;
  if (!vehicle) return null;

  const carWithLights = [
    "pb_plane:car_police",
    "pb_plane:car_fire",
    "pb_plane:car_fire_large",
  ];
  if (!carWithLights.includes(vehicle.typeId)) return null;

  return { vehicle };
}

system.runInterval(() => {
  for (const player of world.getPlayers()) {
    const vehicleCheck = getVehicleData(player);
    if (!vehicleCheck) continue; // Use 'continue' instead of 'return' to avoid stopping the loop

    doubleTapper(player, vehicleCheck.vehicle);
  }
});
