<script setup lang="ts">
const { onRender, onClick, onMouseDown } = useScreen();
const store = useCreditsStore();
const { assets } = useAssets((a) => a.images.credits);

const QUIT_SIZE = assets.quit.rect.width;
const QUIT_X = Math.floor(LOGICAL_WIDTH / 2 - QUIT_SIZE / 2);
const QUIT_Y = 135;

const quitPressed = ref(false);

const handleMouseUp = () => {
  quitPressed.value = false;
};

onMounted(() => document.addEventListener("mouseup", handleMouseUp));
onUnmounted(() => document.removeEventListener("mouseup", handleMouseUp));

onMouseDown((x, y) => {
  if (store.isIntro || store.isOutro) return;
  if (rectContains([QUIT_X, QUIT_Y, QUIT_SIZE, QUIT_SIZE], [x, y])) {
    quitPressed.value = true;
  }
});

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

  switch (key) {
    case "NDS_B":
    case "NDS_A":
    case "NDS_START": {
      store.animateOutro();
    }
  }
});

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

  if (rectContains([QUIT_X, QUIT_Y, QUIT_SIZE, QUIT_SIZE], [x, y])) {
    store.animateOutro();
  }
});

onRender((ctx) => {
  ctx.fillStyle = "#000000";
  ctx.fillRect(0, 0, LOGICAL_WIDTH, LOGICAL_HEIGHT);

  // credits list (bottom screen entries)
  ctx.globalAlpha = store.isIntro
    ? store.intro.stage1Opacity
    : store.isOutro
      ? store.outro.stage1Opacity
      : 1;

  for (let i = CREDITS.length - 1; i >= CREDITS_TOP_SCREEN_COUNT; i--) {
    const id = CREDITS[i]!;
    const offset = store.getItemOffset(i);
    if (offset === -CREDITS_LINE_HEIGHT) continue;

    const baseY =
      CREDITS_BOTTOM_START_Y +
      (i - CREDITS_TOP_SCREEN_COUNT) * CREDITS_ENTRY_HEIGHT;
    const y = baseY + offset;

    ctx.fillStyle = "#000000";
    ctx.fillRect(0, y, LOGICAL_WIDTH, CREDITS_LINE_HEIGHT * 3);

    ctx.fillStyle = "#aaaaaa";
    ctx.font = "7px NDS7";
    fillTextHCentered(
      ctx,
      $t(`creditsScreen.${id}.label`),
      0,
      y + 7,
      LOGICAL_WIDTH,
    );

    ctx.fillStyle = "#ffffff";
    ctx.font = "10px NDS10";
    fillTextHCentered(
      ctx,
      $t(`creditsScreen.${id}.author`),
      0,
      y + CREDITS_LINE_HEIGHT + 9,
      LOGICAL_WIDTH,
    );

    ctx.fillStyle = "#888888";
    ctx.font = "7px NDS7";
    fillTextHCentered(
      ctx,
      $t(`creditsScreen.${id}.url`),
      0,
      y + CREDITS_LINE_HEIGHT * 2 + 7,
      LOGICAL_WIDTH,
    );
  }

  ctx.globalAlpha = store.isIntro
    ? store.intro.stage1Opacity
    : store.isOutro
      ? store.outro.stage2Opacity
      : 1;
  (quitPressed.value ? assets.quitPressed : assets.quit).draw(
    ctx,
    QUIT_X,
    QUIT_Y,
  );
});

defineOptions({
  render: () => null,
});
</script>
