let useGLTF: any = null;

const initializeUseGLTF = async () => {
  if (!useGLTF) {
    try {
      const drei = await import("@react-three/drei");
      useGLTF = drei.useGLTF;
    } catch (error) {
      console.warn(
        "⚠️ GLTFCacheManager: Не удалось импортировать useGLTF",
        error
      );
    }
  }
  return useGLTF;
};

export const clearGLTFCacheForUrl = async (url: string) => {
  try {
    const gltf = await initializeUseGLTF();
    if (gltf && gltf.clear) {
      gltf.clear(url);
    }
  } catch (error) {}
};

export const clearAllGLTFCache = async () => {
  try {
    const gltf = await initializeUseGLTF();
    if (gltf && gltf.clear) {
      gltf.clear();
    }
  } catch (error) {}
};

export const revokeBlobURL = (url: string) => {
  if (url && url.startsWith("blob:")) {
    try {
      URL.revokeObjectURL(url);
    } catch (error) {}
  }
};

export const clearBlobAndGLTFCache = async (url: string) => {
  revokeBlobURL(url);

  await clearGLTFCacheForUrl(url);
};

export const clearMediaTransitionCache = async (
  previousMediaId: string | number | null,
  newMediaType?: number
) => {
  if (newMediaType === 6 || previousMediaId) {
    await clearAllGLTFCache();
  }
};
