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

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

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

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

        if (!hasSneaked && player.isSneaking) {
          // Player just started Sneaking
          player.setDynamicProperty("bps_nc:afterevent_sneaked", true);
          if (callback) {
            callback({
              player: player,
            });
          }
        } else if (hasSneaked && !player.isSneaking) {
          // Player landed on the ground
          player.setDynamicProperty("bps_nc:afterevent_sneaked", undefined);
        }
      });
    }, 1);
  };

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