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

// Ensure the onPlayerJump object exists on world.afterEvents
if (!world.afterEvents.onPlayerJump) {
  world.afterEvents.onPlayerJump = {};
}

// Add the subscribe and unsubscribe methods to world.afterEvents.onPlayerJump
(function () {
  let callback = null;
  let interval = null;

  world.afterEvents.onPlayerJump.subscribe = function (_callback) {
    callback = _callback;
    interval = system.runInterval(() => {
      world.getAllPlayers().forEach((player) => {
        const hasJumped = player.getDynamicProperty("bps_nc:afterevent_jumped");

        if (!hasJumped && player.isJumping) {
          // Player just started jumping
          player.setDynamicProperty("bps_nc:afterevent_jumped", true);
          if (callback) {
            callback({
              player: player,
              blockBelow: player.dimension.getBlock(player.location).below(),
            });
          }
        } else if (hasJumped && (player.isOnGround || !player.isJumping)) {
          // Player landed on the ground
          player.setDynamicProperty("bps_nc:afterevent_jumped", undefined);
        }
      });
    }, 1);
  };

  world.afterEvents.onPlayerJump.unsubscribe = function () {
    if (interval !== null) {
      system.clearRun(interval);
      interval = null;
      callback = null;
    }
  };
})();
