import { Object3D, Vector3 } from "three";

/**
 * Shared anchor for every dish under the Dishes object — matches exported pizza in MenuScene.glb.
 * Unity local (+0.48022, 0, 0.48978) becomes glTF/Three.js X negated on export.
 */
const SHARED_DISH_POSITION = new Vector3(-0.48022, 0, 0.48978);

type DishPlacement = {
  position?: Vector3;
  /** Euler radians (x, y, z) on the dish wrapper. Omit for (0, 0, 0). */
  rotation?: Vector3;
  scale?: Vector3;
};

/**
 * Per-dish scene overrides under Dishes (from MenuScene.unity).
 * Sketchfab scans already bake axis conversion in the GLB — wrapper rotation stays at 0.
 */
const DISH_PLACEMENTS: Record<string, DishPlacement> = {
  quistibi_scan: {
    rotation: new Vector3(0, 0, 0),
    scale: new Vector3(1.1699198, 1.1699204, 1.1699204),
  },
};

/**
 * Keep orientation from the GLB file but move scale/offset to the scene wrapper (like Unity import).
 */
function prepareImportedSceneRoot(gltfScene: Object3D): void {
  gltfScene.position.set(0, 0, 0);
  gltfScene.scale.set(1, 1, 1);
  gltfScene.updateMatrix();
}

/**
 * Wrap a catalog-loaded GLB scene with a dish root that mirrors Unity's prefab instance transform.
 */
export function wrapCatalogDishRoot(
  gltfScene: Object3D,
  dishName: string,
): Object3D {
  const placement = DISH_PLACEMENTS[dishName];

  prepareImportedSceneRoot(gltfScene);

  const wrapper = new Object3D();
  wrapper.name = dishName;
  wrapper.position.copy(placement?.position ?? SHARED_DISH_POSITION);

  const rot = placement?.rotation ?? new Vector3(0, 0, 0);
  wrapper.rotation.set(rot.x, rot.y, rot.z, "XYZ");

  wrapper.scale.copy(placement?.scale ?? new Vector3(1, 1, 1));

  wrapper.add(gltfScene);
  wrapper.updateMatrixWorld(true);
  return wrapper;
}

export function ensureDishVisible(dish: Object3D, active: boolean): void {
  dish.visible = active;
  dish.traverse((child) => {
    child.visible = active;
  });
}
