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

const linkedEntities = new Map();
const linkedOwners = new Map();

export function handleEntity(player) {
  if (linkedEntities.has(player.id)) {
    const entity = linkedEntities.get(player.id);
    if (!entity) return;
    if (!player.isValid()) return;

    const viewVector = player.getViewDirection();
    let distance = player.isSprinting ? 2 : 1;
    distance += player.inputInfo.getMovementVector().y * 1;

    const lateralVector = { x: -viewVector.z, z: viewVector.x };
    let lateralOffset = 0;
    if (Math.abs(player.inputInfo.getMovementVector().x) > 0)
      lateralOffset = player.inputInfo.getMovementVector().x > 0 ? -1.15 : 1.15;

    const newOffset = {
      x:
        player.location.x +
        viewVector.x * distance +
        lateralVector.x * lateralOffset,
      y: player.location.y + 0.6,
      z:
        player.location.z +
        viewVector.z * distance +
        lateralVector.z * lateralOffset,
    };
    if (!entity || !entity.isValid()) return;
    entity.teleport(newOffset);
    return;
  }

  const entity = player.dimension.spawnEntity(
    "lore_hrc:jumpscare",
    player.location
  );
  entity.getComponent(EntityComponentTypes.Tameable)?.tame(player);
  linkedEntities.set(player.id, entity);
  linkedOwners.set(entity.id, player.id);
}

export function removeEntity(player) {
  const entity = linkedEntities.get(player.id);
  if (entity.isValid()) {
    entity.remove();
    linkedOwners.delete(entity.id);
    linkedEntities.delete(player.id);
  }
}
