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

/**
 * Verifica si el jugador mira directamente la cabeza de la Gorgona y aplica efectos.
 * @param {Entity} player
 */
export function isLookingAtHead(player) {
  const targetEntityId = "dungeon:gorgona";
  const initialCommands = [
    "tag @s add stone",
    "scoreboard players reset @s stonetest",
    "inputpermission set @s camera disabled",
    "inputpermission set @s movement disabled"
  ];
  const finalCommands = [
    // Pon tus comandos finales aquí si quieres algo tras 200 ticks
  ];

  const dimension = player.dimension;
  let timer = player.getDynamicProperty("gorgonaTimer") || 0;

  const gameMode = player.getGameMode();
  if (gameMode !== "Survival" && gameMode !== "Adventure") return;

  const entities = dimension.getEntities({
    type: targetEntityId,
    location: player.location,
    maxDistance: 24
  });

  let isLooking = false;

  const playerHeadPos = player.getHeadLocation();
  const direction = player.getViewDirection();

  for (const target of entities) {
    const targetHeadPos = target.getHeadLocation();

    const toTarget = {
      x: targetHeadPos.x - playerHeadPos.x,
      y: targetHeadPos.y - playerHeadPos.y,
      z: targetHeadPos.z - playerHeadPos.z
    };

    const toTargetMagnitude = Math.sqrt(toTarget.x ** 2 + toTarget.y ** 2 + toTarget.z ** 2);
    if (toTargetMagnitude < 0.0001) continue;

    const normalizedToTarget = {
      x: toTarget.x / toTargetMagnitude,
      y: toTarget.y / toTargetMagnitude,
      z: toTarget.z / toTargetMagnitude
    };

    const dotProduct = direction.x * normalizedToTarget.x +
                       direction.y * normalizedToTarget.y +
                       direction.z * normalizedToTarget.z;

    // Evitar precisión flotante extrema
    const aligned = dotProduct > 0.995;

    let isObstructed = false;

    if (aligned) {
      const steps = Math.ceil(toTargetMagnitude * 10);

      for (let i = 1; i < steps; i++) {
        const factor = (i / steps) * toTargetMagnitude;
        const checkPos = {
          x: playerHeadPos.x + normalizedToTarget.x * factor,
          y: playerHeadPos.y + normalizedToTarget.y * factor,
          z: playerHeadPos.z + normalizedToTarget.z * factor
        };

        const block = dimension.getBlock({
          x: Math.floor(checkPos.x),
          y: Math.floor(checkPos.y),
          z: Math.floor(checkPos.z)
        });

        if (block && block.typeId !== "minecraft:air") {
          isObstructed = true;
          break;
        }
      }

      if (!isObstructed) {
        isLooking = true;
        break;
      }
    }
  }

  if (isLooking) {
    timer++;
    try {
      player.runCommand("damage @s 1");
    } catch {}

    if (timer === 1) {
      for (const command of initialCommands) {
        try { player.runCommand(command); } catch {}
      }
    }

    if (timer >= 200) {
      for (const command of finalCommands) {
        try { player.runCommand(command); } catch {}
      }
      timer = 0;
    }
  } else {
    timer = 0;
  }

  player.setDynamicProperty("gorgonaTimer", timer);
}
