import { Box3, Object3D, Vector3 } from "three";

export const INTERACTIVE_ZONE_NAME = "UI_Interactive_Zone_02";
const ZONE_XZ_PADDING = 0.35;

export function findInteractiveZone(root: Object3D): Object3D | null {
  let found: Object3D | null = null;

  root.traverse((child) => {
    if (!found && child.name === INTERACTIVE_ZONE_NAME) {
      found = child;
    }
  });

  return found;
}

export function findInteractiveZoneFromMap(mapObject: Object3D): Object3D | null {
  let sceneRoot: Object3D = mapObject;
  while (sceneRoot.parent) {
    sceneRoot = sceneRoot.parent;
  }

  return findInteractiveZone(sceneRoot);
}

export function refreshInteractiveZoneBounds(zone: Object3D, out = new Box3()) {
  zone.updateWorldMatrix(true, true);
  out.setFromObject(zone);
  out.min.x -= ZONE_XZ_PADDING;
  out.max.x += ZONE_XZ_PADDING;
  out.min.z -= ZONE_XZ_PADDING;
  out.max.z += ZONE_XZ_PADDING;
  return out;
}

export function isInsideInteractiveZoneXZ(bounds: Box3, position: Vector3) {
  return position.x >= bounds.min.x
    && position.x <= bounds.max.x
    && position.z >= bounds.min.z
    && position.z <= bounds.max.z;
}

export function getInteractiveZoneCenter(zone: Object3D, out = new Vector3()) {
  const bounds = refreshInteractiveZoneBounds(zone);
  return bounds.getCenter(out);
}
