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

const ENABLE_3D = true;

type ScreenInstance = InstanceType<typeof NDSScreen>;

const { isReady } = useAssets();

const app = useAppStore();

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

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

const keyToButton: Record<string, string> = {
  ArrowUp: "UP",
  ArrowDown: "DOWN",
  ArrowLeft: "LEFT",
  ArrowRight: "RIGHT",
  d: "A",
  s: "B",
  w: "X",
  a: "Y",
  " ": "SELECT",
  Enter: "START",
};

// 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
useKeyDown((key) => {
  if (ENABLE_3D) return;
  const button = keyToButton[key];
  if (button) {
    window.dispatchEvent(
      new KeyboardEvent("keydown", { key: `NDS_${button}` }),
    );
  }
});

useKeyUp((key) => {
  if (ENABLE_3D) return;
  const button = keyToButton[key];
  if (button) {
    window.dispatchEvent(new KeyboardEvent("keyup", { 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]" />

      <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">
          <IntroTopScreen v-if="!app.booted" />
          <HomeTopScreen v-else-if="app.screen === 'home'" />
          <ContactTopScreen v-else-if="app.screen === 'contact'" />
          <ProjectsTopScreen v-else-if="app.screen === 'projects'" />
          <SettingsTopScreen v-else-if="app.screen === 'settings'" />
          <GalleryTopScreen v-else-if="app.screen === 'gallery'" />
        </Screen>
      </div>
      <div>
        <Screen ref="bottomScreen">
          <IntroBottomScreen v-if="!app.booted" />
          <HomeBottomScreen v-else-if="app.screen === 'home'" />
          <ContactBottomScreen v-else-if="app.screen === 'contact'" />
          <ProjectsBottomScreen v-else-if="app.screen === 'projects'" />
          <SettingsBottomScreen v-else-if="app.screen === 'settings'" />
          <GalleryBottomScreen v-else-if="app.screen === 'gallery'" />
        </Screen>
      </div>
    </div>
  </div>
</template>
