import { system, TicksPerSecond, EntityComponentTypes, world } from "@minecraft/server";
import { smoothTeleport, getExactLookLocation } from "../items/skull_hook";
import V3 from "../utilities/V3";

world.afterEvents.entityDie.subscribe((eventData) => {
  const entity = eventData.deadEntity;

  if (entity.typeId !== "cyd_dino:skull_trex_boss") return;

  entity.dimension.getEntities({
    type: "cyd_dino:dark_draxar_boss",
    location: entity.location,
    maxDistance: 20,
    closest: 1
  }).forEach(boss => {
    if (!boss || !boss.isValid()) return;

    boss.addTag("cyd_dino:trex_defeated");
  })

});



system.afterEvents.scriptEventReceive.subscribe((eventData) => {
  if (eventData.id !== "cyd_dino:test") return;

  const player = eventData.sourceEntity;

  if (!player) return;

  const boss = player.dimension.getEntities({
    location: player.location,
    maxDistance: 20,
    type: "cyd_dino:dark_draxar_boss"
  })[0];
  if (!boss) return;

  spawnBossProjectile(boss, player);
});

system.afterEvents.scriptEventReceive.subscribe((eventData) => {
  if (eventData.id !== "cyd_dino:spawn_boss") return;

  const player = eventData.sourceEntity;

  if (!player) return;

  const trex = player.dimension.spawnEntity("cyd_dino:skull_trex", player.location);
  const dark_draxar_boss = player.dimension.spawnEntity("cyd_dino:dark_draxar_boss", player.location);
  trex.getComponent("minecraft:rideable").addRider(dark_draxar_boss);
});


function rotateToward(entity, target) {
  const test = entity.getComponent(EntityComponentTypes.Riding)?.entityRidingOn;

  if (test && test.isValid()) return;

  entity.teleport(entity.location, { facingLocation: target.location });
}

/**
 * 
 * @param {Entity} boss 
 * @param {Player} player 
 */
async function spawnBossProjectile(boss, player) {
  rotateToward(boss, player);

  let dest = null;

  if (player) {
    try {
      // Determine the ray distance to the player and raycast to find blocks in the way.
      const bossPos = new V3(boss.location);
      const playerPos = new V3(player.location);
      const dir = playerPos.subtract(bossPos).normalize();

      
      player.addEffect("slowness", 2 * TicksPerSecond, { amplifier: 5, showParticles: false });

      dest = new V3(boss.location).add(new V3(dir.x, 0, dir.z).normalize().scale(1));
      dest.y = boss.location.y;

    } catch (e) {
      dest = null;
    }
  }

  // Fallback: if we didn't early-return above, aim directly at the player's position and carry them.
  smoothTeleport(boss, player.location, 1, player, dest);
}