import { system, world } from "@minecraft/server";
import { fo } from "./utilities/fo_constants";


export function initCamera() {

  const chance = 1 / 60; 
  const RAYCAST_MAX_DISTANCE = 30; 
  const STEP_SIZE = 1; 
  const checkInterval = 2403; 

  system.runInterval(() => {
    const forebodingScore = fo.forebodingScore;

    if (forebodingScore >= fo.scoreChapter4 && Math.random() < (chance * fo.netProbabilityModifier)) { 
      const players = world.getPlayers();
      if (players.length > 0) {
        const randomPlayer = getRandomPlayer(players);
        triggerCameraEvent(randomPlayer);
      }
    }
  }, checkInterval); 

  function triggerCameraEvent(player) {
    const raycastPos = getRaycastPosition(player, RAYCAST_MAX_DISTANCE);

    if (raycastPos) {
      player.runCommand(`camera @s set minecraft:free pos ${raycastPos.x} ${raycastPos.y} ${raycastPos.z} facing @s`);
      
    }

    
    system.runTimeout(() => {
      player.runCommand("camera @s clear");
    }, 20); 
  }

  function getRaycastPosition(player, maxDistance) {
    let { x, y, z } = player.location;
    y += 1.6;
    const direction = getViewDirection(player);

    if (!direction) {
      
      return null;
    }

    for (let i = 0; i < maxDistance; i += STEP_SIZE) {
      x += direction.x * STEP_SIZE;
      y += direction.y * STEP_SIZE;
      z += direction.z * STEP_SIZE;

      const block = player.dimension.getBlock({ x: Math.floor(x), y: Math.floor(y), z: Math.floor(z) });
      if (block && block.typeId !== "minecraft:air") {
        return { x, y, z };
      }
    }

    return {
      x: player.location.x + direction.x * maxDistance,
      y: player.location.y + 1.6 + direction.y * maxDistance,
      z: player.location.z + direction.z * maxDistance,
    };
  }

  function getViewDirection(player) {
    let rotation = player.getRotation();

    if (!rotation || rotation.x === undefined || rotation.y === undefined) {
      
      return { x: 0, y: 0, z: 1 }; 
    }

    const pitch = (rotation.x * Math.PI) / 180;
    const yaw = ((rotation.y + 90) * Math.PI) / 180;

    return {
      x: Math.cos(pitch) * Math.cos(yaw) * -1,
      y: Math.sin(pitch),
      z: Math.cos(pitch) * Math.sin(yaw) * -1,
    };
  }

  function getRandomPlayer(players) {
    const randomIndex = Math.floor(Math.random() * players.length);
    return players[randomIndex];
  }

}