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

const store = useIntroStore();
const { onRender, onClick } = useScreen();
const { assets } = useAssets();

const TITLE_Y = 25;
const TEXT_Y = 63;
const HINT_Y = 167;

const hintTextOpacity = ref(0);

store.$subscribe((_, state) => {
  if (!state.isIntro && !state.isOutro) {
    gsap.to(hintTextOpacity, {
      value: 1,
      duration: 0.5,
      repeat: -1,
      yoyo: true,
      ease: "none",
    });
  }
});

onRender((ctx) => {
  ctx.textBaseline = "top";

  ctx.fillStyle = "#fbfbfb";
  ctx.fillRect(0, 0, LOGICAL_WIDTH, LOGICAL_HEIGHT);

  ctx.fillStyle = "#000000";

  // title
  ctx.font = "12px NDS12 Bold";
  ctx.letterSpacing = "1px";

  const { actualBoundingBoxRight: width } = ctx.measureText(
    $t("intro.copyright"),
  );

  const logoWidth = assets.images.intro.warning.rect.width;
  const logoX = Math.floor(LOGICAL_WIDTH / 2 - (width + logoWidth + 3) / 2);

  ctx.globalAlpha = store.isIntro
    ? store.intro.textOpacity
    : store.isOutro
      ? store.outro.textOpacity
      : 1;

  assets.images.intro.warning.draw(ctx, logoX, TITLE_Y - 1);
  ctx.fillText($t("intro.copyright"), logoX + logoWidth + 3, TITLE_Y);

  ctx.letterSpacing = "0px";

  // text
  ctx.font = "10px NDS10";
  const lines = $t("intro.text").split("\n");
  for (let i = 0, y = TEXT_Y; i < lines.length; i += 1, y += 18)
    fillTextHCentered(ctx, lines[i]!, 0, y, LOGICAL_WIDTH);

  // hint
  ctx.font = "10px NDS10";
  ctx.globalAlpha = store.isIntro
    ? 0
    : store.isOutro
      ? store.outro.textOpacity
      : hintTextOpacity.value;
  fillTextHCentered(ctx, $t("intro.hint"), 0, HINT_Y, LOGICAL_WIDTH);

  ctx.globalAlpha = store.isOutro ? store.outro.backgroundOpacity : 0;
  assets.images.home.topScreen.background.draw(ctx, 0, 0);
});

onClick(() => {
  if (store.isIntro || store.isOutro) return;

  store.animateOutro();
});

useKeyDown((key) => {
  if (store.isIntro || store.isOutro) return;

  switch (key) {
    case "NDS_A":
    case "NDS_START":
      store.animateOutro();
      break;
  }
});
</script>

<template>
  <div />
</template>
