"use client";
import Image from "next/image";
import { useSearchParams } from "next/navigation";
import { Suspense } from "react";
import { Unity, UnityConfig, useUnityContext } from "react-unity-webgl";
const unityConfigBuilder: (path: string) => UnityConfig = (path) => ({
  loaderUrl: `${path}.loader.js`,
  dataUrl: `${path}.data`,
  frameworkUrl: `${path}.framework.js`,
  codeUrl: `${path}.wasm`,
  streamingAssetsUrl: "StreamingAssets",
  companyName: "DTOL",
  productName: "3d-test",
  productVersion: "0.1",
});

const option = [
  { value: "/unity/3d-test/Build/3d-test", name: "3d-test" },
  { value: "/unity/test-project/build", name: "test-project" },
];

function UnityComponent() {
  const params = useSearchParams();
  const p = params.get("p");
  console.log(p);
  if (!p || isNaN(Number(p))) location.href = "/unity?p=0";

  const {
    unityProvider,
    isLoaded,
    loadingProgression,
    initialisationError,
    UNSAFE__unityInstance,
  } = useUnityContext(unityConfigBuilder(option[Number(p)].value));

  const loadingPercentage = Math.round(loadingProgression * 100);

  return (
    <>
      <div className="mb-5 mt-5">
        새 Unity 프로젝트를 생성하고, WebGL로 빌드 후 빌드 산출물을
        react-unity-webgl 라이브러리를 통해 실행했다.
      </div>
      <div className="flex h-[650px] w-[800px] flex-col">
        {isLoaded === false && (
          <div className="absolute z-10 flex h-[600px] w-[800px] items-center justify-center bg-gray-500">
            <p>Loading... ({loadingPercentage}%)</p>
          </div>
        )}
        <Unity className="h-[600px] w-[800px]" unityProvider={unityProvider} />
        <div className="mt-auto flex">
          <select
            value={Number(p)}
            onChange={(e) => (location.href = `/unity?p=${e.target.value}`)}
            className="mt-5"
          >
            {option.map((o, i) => (
              <option key={`${o}-${i}`} value={i}>
                {o.name}
              </option>
            ))}
          </select>
          <Image
            src={"/unity/3d-test/TemplateData/fullscreen-button.png"}
            alt="전체 화면 버튼"
            title="전체 화면으로 보기"
            width={38}
            height={38}
            className="ml-auto mt-2 cursor-pointer"
            onClick={() => UNSAFE__unityInstance?.SetFullscreen(1)}
          />
        </div>
      </div>
    </>
  );
}

export default function UnityWrapper() {
  return (
    <Suspense>
      <UnityComponent />
    </Suspense>
  );
}
