<script setup lang="ts">
import type { Screen as NDSScreen } from "#components";

// TODO: keys doesn't work anymore if 3D modea is disabled
const ENABLE_3D = false;

type ScreenInstance = InstanceType<typeof NDSScreen>;

const { isReady } = useAssets();

const route = useRoute();
const screen = computed(() => route.query.screen as string | undefined);

const topScreen = useTemplateRef<ScreenInstance>("topScreen");
const bottomScreen = useTemplateRef<ScreenInstance>("bottomScreen");

const topScreenCanvas = computed(() => topScreen.value?.canvas ?? null);
const bottomScreenCanvas = computed(() => bottomScreen.value?.canvas ?? null);

useKeyDown((key) => {
  // events are dispatched from NDS.vue in 3d mode
  // events are dispatched from here in 2d mode
  // that's a bit dirty but who cares, there is a lot of dirty things going on here
  // like who choose Nuxt to build such an app
  if (ENABLE_3D) return;
  const keyToButton: Record<string, string> = {
    ArrowUp: "UP",
    ArrowDown: "DOWN",
    ArrowLeft: "LEFT",
    ArrowRight: "RIGHT",
    d: "A",
    s: "B",
    w: "X",
    a: "Y",
    " ": "SELECT",
    Enter: "START",
  };
  const button = keyToButton[key];
  if (button) {
    window.dispatchEvent(
      new KeyboardEvent("keydown", { key: `NDS_${button}` }),
    );
  }
});
</script>

<template>
  <LoadingScreen v-if="!isReady" />
  <div v-else>
    <TresCanvas v-if="ENABLE_3D" window-size clear-color="#181818">
      <TresPerspectiveCamera
        :args="[45, 1, 0.001, 1000]"
        :position="[0, 10, 12]"
        :rotation="[-Math.PI / 4.7, 0, 0]"
      />

      <TresAmbientLight />
      <TresDirectionalLight />

      <NDS
        v-if="topScreenCanvas && bottomScreenCanvas"
        :top-screen-canvas="topScreenCanvas"
        :bottom-screen-canvas="bottomScreenCanvas"
      />
    </TresCanvas>

    <div :style="{ visibility: ENABLE_3D ? 'hidden' : 'visible' }">
      <div>
        <Screen ref="topScreen">
          <HomeTopScreen v-if="!screen" />
          <ContactTopScreen v-else-if="screen === 'contact'" />
          <ProjectsTopScreen v-else-if="screen === 'projects'" />
          <SettingsTopScreen v-else-if="screen === 'settings'" />
        </Screen>
      </div>
      <div>
        <Screen ref="bottomScreen">
          <HomeBottomScreen v-if="!screen" />
          <ContactBottomScreen v-else-if="screen === 'contact'" />
          <ProjectsBottomScreen v-else-if="screen === 'projects'" />
          <SettingsBottomScreen v-else-if="screen === 'settings'" />
        </Screen>
      </div>
    </div>
  </div>
</template>
