import { Camera, Vector3 } from "three";

// Scratch vector reused across calls so projecting never allocates per frame.
const _ndc = new Vector3();

/**
 * Project a world-space point to screen pixels.
 *
 * `camera.project()` gives Normalized Device Coordinates (NDC): the visible area
 * maps to -1..1 on both axes, with +Y up. We remap that to CSS pixels and offset
 * by the canvas position on the page (`canvasRect`), flipping Y because the DOM
 * grows downward. Used to fly HTML elements (loot, planks) to/from 3D objects.
 */
export function worldToScreen(
  world: Vector3,
  camera: Camera,
  canvasRect: DOMRect,
): { x: number; y: number } {
  _ndc.copy(world).project(camera);
  return {
    x: canvasRect.left + (_ndc.x * 0.5 + 0.5) * canvasRect.width,
    y: canvasRect.top + (-_ndc.y * 0.5 + 0.5) * canvasRect.height,
  };
}
