import { useLoader } from "@react-three/fiber";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { clone } from "three/examples/jsm/utils/SkeletonUtils";

interface MultiGLTFInstancesProps {
  index: number;
  modelUrl: string;
  position: [number, number, number];
  rotation: [number, number, number];
}

export const MultiGLTFInstances: React.FC<MultiGLTFInstancesProps> = ({
  index,
  modelUrl,
  position,
  rotation,
}) => {
  // Load GLTF model with DRACO loader for compression
  const originalGltf = useLoader(GLTFLoader, modelUrl, (loader) => {
    const draco = new DRACOLoader();
    draco.setDecoderPath(
      "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/libs/draco/"
    );
    loader.setDRACOLoader(draco);
  });

  // Clone the model for independent transformations
  const cloned = clone(originalGltf.scene);

  // Render the cloned model
  return (
    <mesh>
      <primitive
        name="rigged_arm"
        key={index}
        object={cloned}
        position={position}
        rotation={rotation}
      />
    </mesh>
  );
};
