import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js';
import { KTX2Loader } from 'three/examples/jsm/loaders/KTX2Loader.js';
import { publicAssetUrl } from '../runtimeBase';

export interface ViewerLoaders {
  gltf: GLTFLoader;
  draco: DRACOLoader;
  ktx2: KTX2Loader;
}

// SINGLETON — multiple DRACOLoader/KTX2Loader instances crash (three.js #22445).
// Reuse across every load. Decoder WASM lives under public/draco + public/basis
// (version-matched to the installed three.js).
let _cache: ViewerLoaders | null = null;

export function getLoaders(renderer: THREE.WebGLRenderer): ViewerLoaders {
  if (_cache) return _cache;
  const draco = new DRACOLoader().setDecoderPath(publicAssetUrl('draco/'));
  const ktx2 = new KTX2Loader()
    .setTranscoderPath(publicAssetUrl('basis/'))
    .detectSupport(renderer);
  const gltf = new GLTFLoader().setDRACOLoader(draco).setKTX2Loader(ktx2);
  _cache = { gltf, draco, ktx2 };
  return _cache;
}
