import { useGLTF } from "@react-three/drei";
import { useThree } from "@react-three/fiber";
import { createContext, useContext, useEffect, useState, type ReactNode } from "react";
import { KTX2Loader } from "three-stdlib";

const BASIS_TRANSCODER_PATH = `${import.meta.env.BASE_URL}basis/`;
const query = typeof window === "undefined" ? null : new URLSearchParams(window.location.search);

export const LEGACY_GAME_ASSETS_FORCED = import.meta.env.VITE_LEGACY_GAME_ASSETS === "1"
  || import.meta.env.VITE_LEGACY_DUNGEON_ASSETS === "1"
  || query?.has("legacyGameAssets") === true
  || query?.has("legacyDungeonAssets") === true;

const Ktx2LoaderContext = createContext<KTX2Loader | null>(null);

export function selectedGameAssetUrl(legacyUrl: string, optimizedUrl: string) {
  return LEGACY_GAME_ASSETS_FORCED ? legacyUrl : optimizedUrl;
}

export function GameAssetProvider({ children }: { children: ReactNode }) {
  const gl = useThree((state) => state.gl);
  const [ktx2Loader] = useState(() => LEGACY_GAME_ASSETS_FORCED
    ? null
    : new KTX2Loader().setTranscoderPath(BASIS_TRANSCODER_PATH).detectSupport(gl));

  useEffect(() => () => {
    ktx2Loader?.dispose();
  }, [ktx2Loader]);

  return <Ktx2LoaderContext.Provider value={ktx2Loader}>{children}</Ktx2LoaderContext.Provider>;
}

export function useGameGLTF(url: string) {
  const ktx2Loader = useContext(Ktx2LoaderContext);
  return useGLTF(
    url,
    false,
    true,
    (loader) => {
      if (ktx2Loader) loader.setKTX2Loader(ktx2Loader);
    },
  );
}
