import { world, system } from "@minecraft/server";
import { isRedMoon } from "../moon/moon_handler";

export function jumpScareAnim(player) {
  if (isRedMoon() || player.dimension.id != "minecraft:overworld") return;
  animateJumpscare(player);
}
export function jumpScareInit() {
  let lastInteractionTime = 0;
  const DEBOUNCE_TIME = 100; // 100 milliseconds debounce time
  world.afterEvents.playerInteractWithBlock.subscribe((event) => {
    const player = event.player;
    const block = event.block;
    if (isRedMoon() || player.dimension.id != "minecraft:overworld") return;
    const currentTime = Date.now();
    if (currentTime - lastInteractionTime < DEBOUNCE_TIME) return;
    lastInteractionTime = currentTime;
    if (block.typeId != "minecraft:bed" && event.isFirstEvent) return;
    const playerJumpscareTag = "hb_hr:" + player.id;
    if (player.isSleeping) {
      // 0.2 = 20% that a jumpscare happens this night
      const jumpScareChance = 0.15;
      const randomJumpScareChance = Math.random();
      if (player.hasTag("hb_hr:jumpscare_movement")) return;
      const timeUntilJumpscare = 40 + Math.random() * 20;
      if (randomJumpScareChance > jumpScareChance) return;
      else {
        system.waitTicks(timeUntilJumpscare).then(() => {
          if (player.hasTag("hb_hr:jumpscare_movement")) return;
          const bedLocation = player.location;
          randomTeleport(player, 4);
          player.camera.setCamera("minecraft:first_person");
          player.runCommand("/tp @s ~ ~ ~ 0 -180");
          player.addTag("hb_hr:jumpscare_movement");
          player.runCommand(`/inputpermission set @s movement disabled`);
          player.runCommand(`/inputpermission set @s camera disabled`);
          player.playSound("hb_hr_jumpscare", player.location);
          player.runCommand("/camerashake add @s 0.2 2 positional");
          player.runCommand("/tp @s ~ ~ ~ 0 -180");
          let jumpScare = player.dimension.spawnEntity("hb_hr:jumpscare", { x: player.location.x, y: player.location.y + 1, z: player.location.z });
          jumpScare.addTag(playerJumpscareTag);
          jumpScare.playAnimation("animation.hb_hr.jumpscare.turn_on", { players: [player.name] });
          system.runTimeout(() => {
            player.runCommand("/tp @s ~ ~ ~ facing " + Math.floor(bedLocation.x) + " " + Math.floor(bedLocation.y) + " " + Math.floor(bedLocation.z) + " ");
            player.runCommand("/stopsound @s raid.horn");
            player.removeTag("hb_hr:jumpscare_movement");
            player.runCommand(`/inputpermission set @s movement enabled`);
            player.runCommand(`/inputpermission set @s camera enabled`);
            player.runCommand("/camera @s clear");
            player.camera.clear();
          }, 30);
        });
      }
    }
  });
}

function animateJumpscare(player) {
  const playerJumpscareTag = "hb_hr:" + player.id;
  const timeOfDay = world.getTimeOfDay();
  const isNight = timeOfDay >= 12500 && timeOfDay <= 23500;
  if (!isNight) return;
  const allJumpscares = player.dimension.getEntities({ type: "hb_hr:jumpscare", tags: [playerJumpscareTag] });
  try {
    if (allJumpscares.length > 0) {
      allJumpscares.forEach((jumpscare) => {
        if (!jumpscare.isValid()) return;
        jumpscare.playAnimation("animation.hb_hr.jumpscare.turn_on", { players: [player.name] });
      });
    }
  } catch (error) {}
}
function randomTeleport(entity, teleportRange) {
  const dimension = world.getDimension(entity.dimension.id);
  const location = entity.location;
  const blockDetails = dimension.getBlockFromRay(
    // this gets us the block details, NOT the block itself
    { x: location.x + Math.floor(Math.random() * (teleportRange - -teleportRange + 1)) + -teleportRange, y: location.y + 100, z: location.z + Math.floor(Math.random() * (teleportRange - -teleportRange + 1)) + -teleportRange }, // starting from the entity location
    { x: 0, y: -1, z: 0 }, // look down
    { maxDistance: 300 } // for 300 blocks
  );

  if (blockDetails) {
    // if blockDetails exists, so NOT undefined
    const groundLocation = blockDetails.block.location; // make sure we get the block itself
    // entity.dimension.spawnParticle("hb_ml:teleport_1", location);
    // entity.dimension.spawnParticle("hb_ml:teleport_2", { x: groundLocation.x + 0.5, y: groundLocation.y + 1, z: groundLocation.z + 0.5 });
    entity.teleport(
      {
        x: groundLocation.x + 0.5, // set the center of the block
        y: groundLocation.y + 1, // teleport the player on top of the block
        z: groundLocation.z + 0.5, // set the center of the block
      },
      { keepVelocity: false }
    );
  }
}
