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

const store = useSettingsStore();

const { onRender } = useScreen();
const { assets: atlas } = useAssets();
const assets = atlas.images.settings.bottomScreen;

const USER_NAME = "pihkaal";
const REAL_NAME = "Stevan";

const SLIDE_OFFSET = 48;
const SLIDE_DURATION = 0.15;
const OUTRO_OFFSET = 96;
const OUTRO_DURATION = 0.25;
const ROW_STAGGER = SLIDE_DURATION + 0.075;
const ROW_COUNT = 2;

const animation = reactive({
  rowOffsetY: new Array<number>(ROW_COUNT).fill(SLIDE_OFFSET),
  rowOpacity: new Array<number>(ROW_COUNT).fill(0),
});

const animateIntro = async () => {
  const timeline = gsap.timeline();
  for (let i = 0; i < ROW_COUNT; i++) {
    timeline
      .to(
        animation.rowOffsetY,
        { [i]: 0, duration: SLIDE_DURATION, ease: "none" },
        i * ROW_STAGGER,
      )
      .to(
        animation.rowOpacity,
        { [i]: 1, duration: SLIDE_DURATION, ease: "none" },
        i * ROW_STAGGER,
      );
  }
  await timeline;
};

const animateOutro = async () => {
  const timeline = gsap.timeline();
  for (let i = 0; i < ROW_COUNT; i++) {
    timeline
      .to(
        animation.rowOffsetY,
        { [i]: OUTRO_OFFSET, duration: OUTRO_DURATION, ease: "none" },
        0,
      )
      .to(
        animation.rowOpacity,
        { [i]: 0, duration: OUTRO_DURATION, ease: "none" },
        0,
      );
  }
  await timeline;
};

onMounted(() => {
  animateIntro();
});

const handleCancel = async () => {
  await animateOutro();
  store.closeSubMenu();
};

const handleConfirm = async () => {
  await animateOutro();
  store.closeSubMenu();
};

onRender((ctx) => {
  ctx.font = "10px NDS10";
  ctx.textBaseline = "top";

  assets.background.draw(ctx, 0, 0);

  const drawTextField = (
    title: string,
    text: string,
    x: number,
    y: number,
  ): void => {
    // title
    ctx.fillStyle = "#282828";
    assets.user.nameTitle.draw(ctx, x + 12, y);
    fillTextHCentered(ctx, title, x + 12, y + 4, 169);

    // field
    ctx.fillStyle = "#fbfbfb";
    assets.user.nameField.draw(
      ctx,
      x,
      y + assets.user.nameTitle.rect.height - 1,
    );

    for (let i = 0; i < text.length; i += 1, x += 16) {
      ctx.fillText(text[i]!, x + 20, y + assets.user.nameTitle.rect.height + 3);
    }
  };

  ctx.save();
  ctx.globalAlpha = animation.rowOpacity[0]!;
  ctx.translate(0, animation.rowOffsetY[0]!);
  drawTextField($t("settings.user.userName.userName"), USER_NAME, 31, 48);
  ctx.restore();

  ctx.save();
  ctx.globalAlpha = animation.rowOpacity[1]!;
  ctx.translate(0, animation.rowOffsetY[1]!);
  drawTextField($t("settings.user.userName.firstName"), REAL_NAME, 31, 96);
  ctx.restore();
});

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

<template>
  <CommonButtons
    :y-offset="0"
    :b-label="$t('common.cancel')"
    :a-label="$t('common.confirm')"
    @activate-b="handleCancel"
    @activate-a="handleConfirm"
  />
</template>
