import { PointerEventTypes } from '@babylonjs/core';

/**
 * Babylon scene picking -> React callback. Never touches Base44 records.
 * Selection failures are swallowed so they cannot crash the viewport.
 */
export function createSelectionManager(scene, onSelect) {
  if (!scene) return { dispose: () => {} };
  let observer = null;
  try {
    observer = scene.onPointerObservable.add((pi) => {
      if (pi.type !== PointerEventTypes.POINTERTAP) return;
      try {
        const pick = pi.pickInfo;
        if (pick && pick.hit && pick.pickedMesh && pick.pickedMesh.metadata) {
          onSelect(pick.pickedMesh.metadata, pick.pickedMesh);
        } else {
          onSelect(null, null);
        }
      } catch (_) { /* ignore */ }
    });
  } catch (_) { /* ignore */ }

  return {
    dispose: () => { try { if (observer) observer.remove(); } catch (_) {} },
  };
}