<script setup lang="ts">
import gsap from "gsap";

const selectorImage = useTemplateRef("selectorImage");
const projectSquareImage = useTemplateRef("projectSquareImage");

const projects = ["a", "b", "c", "d", "e", "f", "g", "h"];
let currentProject = 0;
const offsetX = ref(0);

useRender((ctx) => {
  if (!selectorImage.value || !projectSquareImage.value) return;

  const startIndex = Math.max(currentProject - 3, 0);
  const endIndex = Math.min(currentProject + 3 + 1, projects.length);

  for (let i = startIndex; i < endIndex; i += 1) {
    const offsetFromCenter = i - currentProject;
    const x = 101 + 69 * offsetFromCenter + offsetX.value;

    ctx.drawImage(projectSquareImage.value, x, 81);
  }

  ctx.drawImage(selectorImage.value, 96, 76);

  ctx.font = "10px NDS10";
  ctx.fillText(projects[currentProject]!, 20, 20);
});

const handleKeyDown = (e: KeyboardEvent) => {
  let from = 0;
  if (e.key === "ArrowRight" && currentProject < projects.length - 1) {
    currentProject += 1;
    from = 69;
  }
  if (e.key === "ArrowLeft" && currentProject > 0) {
    currentProject -= 1;
    from = -69;
  }

  if (from != 0) {
    gsap.fromTo(
      offsetX,
      {
        value: from,
      },
      {
        value: 0,
        duration: 0.075,
        ease: "none",
      },
    );
  }
};

onMounted(() => window.addEventListener("keydown", handleKeyDown));
onUnmounted(() => window.removeEventListener("keydown", handleKeyDown));
</script>

<template>
  <img
    ref="selectorImage"
    src="/assets/images/projects/bottom-screen/selector.png"
    hidden
  />
  <img
    ref="projectSquareImage"
    src="/assets/images/projects/bottom-screen/project-square.png"
    hidden
  />
</template>
