import { Behaviour } from "@needle-tools/engine";
import type { PointerEventData } from "@needle-tools/engine";
import { findMenuController } from "../findMenuController.js";
import { isArSessionActive, toggleIngredientsPanel } from "../ingredientsPopup.js";
import type { Object3D } from "three";

/**
 * On mesh tap in AR, open the ingredients panel for the parent dish root.
 */
export class DishIngredientsTap extends Behaviour {
  onPointerClick(_args: PointerEventData): void {
    if (!isArSessionActive(this.context)) return;

    const dishRoot = this.resolveDishRoot();
    if (!dishRoot) return;

    toggleIngredientsPanel(this.context, dishRoot.name);
  }

  private resolveDishRoot(): Object3D | null {
    const menu = findMenuController(this.context);
    if (menu) {
      for (const dish of menu.dishes) {
        if (!dish) continue;
        let node: Object3D | null = this.gameObject;
        while (node) {
          if (node === dish) return dish;
          node = node.parent;
        }
      }
    }
    return this.gameObject;
  }
}
