<script setup lang="ts">
import gsap from "gsap";
import SELECTOR_IMAGE from "/assets/images/projects/bottom-screen/selector.png";
import PROJECT_SQUARE_IMAGE from "/assets/images/projects/bottom-screen/project-square.png";

const store = useProjectsStore();

const [selectorImage, projectSquareImage] = useImages(
  SELECTOR_IMAGE,
  PROJECT_SQUARE_IMAGE,
);
const projectThumbnails = useImages(...store.projects.map((x) => x.thumbnail));

const offsetX = ref(0);

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

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

    ctx.drawImage(projectSquareImage!, x, 81);
    ctx.drawImage(projectThumbnails[i]!, x + 7, 88);
  }

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

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

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