import type { Camera, Vector2 } from 'three';
import { Vector3 } from 'three';
import type { Size } from '@react-three/fiber';
import type { Quadrangle } from '@map/types';

const screenCorners = () =>
  [
    [-1, 1],
    [1, 1],
    [1, -1],
    [-1, -1]
  ].map(([x, z]) => {
    return new Vector3(x, z, 0);
  });

export function getScreenToWorldPoint(screenPoint: Vector3, camera: Camera, height = 0) {
  const position = new Vector3();

  screenPoint.unproject(camera);
  screenPoint.sub(camera.position).normalize();

  // height is planeZ
  const distance = (height - camera.position.z) / screenPoint.z;

  position.copy(camera.position).add(screenPoint.multiplyScalar(distance));

  return position;
}

export function getScreenArea(camera: Camera, height = 0): Quadrangle {
  return screenCorners().map((corner) => {
    const point = getScreenToWorldPoint(corner, camera, height);

    return {
      x: point.x,
      y: point.y
    };
  }) as Quadrangle;
}

export function getScreenPoint(screenPosition: Vector2, screen: Size) {
  return new Vector3((screenPosition.x / screen.width) * 2 - 1, -(screenPosition.y / screen.height) * 2 + 1, 0);
}
