<script setup lang="ts">
import { SettingsBottomScreenNumberInput as NumberInput } from "#components";
import { useIntervalFn } from "@vueuse/core";
import gsap from "gsap";

const store = useSettingsStore();
const { assets } = useAssets();
const { onRender } = useScreen();

const now = ref(new Date());

useIntervalFn(() => {
  now.value = new Date();
}, 1000);

const SLIDE_OFFSET = 96;
const SLIDE_DURATION = 0.25;

const animation = reactive({
  offsetY: SLIDE_OFFSET,
  opacity: 0,
});

const isAnimating = ref(true);

const hourRef = useTemplateRef<InstanceType<typeof NumberInput>>("hour");
const minuteRef = useTemplateRef<InstanceType<typeof NumberInput>>("minute");

const animateIntro = async () => {
  isAnimating.value = true;
  await Promise.all([
    hourRef.value?.animateIntro(),
    minuteRef.value?.animateIntro(),
    gsap
      .timeline()
      .to(animation, { offsetY: 0, duration: SLIDE_DURATION, ease: "none" }, 0)
      .to(animation, { opacity: 1, duration: SLIDE_DURATION, ease: "none" }, 0),
  ]);
  isAnimating.value = false;
};

const animateOutro = async () => {
  isAnimating.value = true;
  await Promise.all([
    hourRef.value?.animateOutro(),
    minuteRef.value?.animateOutro(),
    gsap
      .timeline()
      .to(
        animation,
        { offsetY: SLIDE_OFFSET, duration: SLIDE_DURATION, ease: "none" },
        0,
      )
      .to(animation, { opacity: 0, duration: SLIDE_DURATION, ease: "none" }, 0),
  ]);
};

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

const handleActivateB = async () => {
  if (isAnimating.value) return;
  await animateOutro();
  store.closeSubMenu();
};

const handleActivateA = async () => {
  if (isAnimating.value) return;
  await animateOutro();
  store.closeSubMenu();
};

onRender((ctx) => {
  ctx.globalAlpha = animation.opacity;
  ctx.translate(0, animation.offsetY);
  assets.images.settings.bottomScreen.clock.timeColon.draw(ctx, 112, 63);
});

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

<template>
  <NumberInput
    ref="hour"
    :model-value="now.getHours()"
    :title="$t('settings.clock.time.hour')"
    :x="4 * 16 - 1"
    :disabled="true"
  />
  <NumberInput
    ref="minute"
    :model-value="now.getMinutes()"
    :title="$t('settings.clock.time.minute')"
    :x="9 * 16 - 1"
    :disabled="true"
  />

  <CommonButtons
    :y-offset="store.submenuButtonsOffsetY"
    :b-label="$t('common.cancel')"
    :a-label="$t('common.confirm')"
    @activate-b="handleActivateB"
    @activate-a="handleActivateA"
  />
</template>
