<script setup lang="ts">
import { OrbitControls } from "@tresjs/cientos";

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

const topScreen = useTemplateRef("topScreen");
const bottomScreen = useTemplateRef("bottomScreen");

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

const handleScreenClick = (
  canvas: HTMLCanvasElement | null,
  x: number,
  y: number,
) => {
  if (!canvas) return;

  const rect = canvas.getBoundingClientRect();
  const clickEvent = new MouseEvent("click", {
    bubbles: true,
    cancelable: true,
    clientX: (x / SCREEN_WIDTH) * rect.width + rect.left,
    clientY: (y / SCREEN_HEIGHT) * rect.height + rect.top,
  });
  canvas.dispatchEvent(clickEvent);
};
</script>

<template>
  <div>
    <TresCanvas window-size clear-color="#181818">
      <TresPerspectiveCamera :args="[45, 1, 0.001, 1000]" />
      <OrbitControls />

      <TresAmbientLight />
      <TresDirectionalLight />

      <NDS
        v-if="topScreenCanvas && bottomScreenCanvas"
        :top-screen-canvas="topScreenCanvas"
        :bottom-screen-canvas="bottomScreenCanvas"
        @top-screen-click="(x, y) => handleScreenClick(topScreenCanvas, x, y)"
        @bottom-screen-click="
          (x, y) => handleScreenClick(bottomScreenCanvas, x, y)
        "
      />
    </TresCanvas>

    <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>
    <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>
</template>
