<script setup lang="ts">
import { LazyGalleryModal } from "#components";
import type { InternalApi } from "nitropack/types";
import { promiseTimeout, useElementSize } from "@vueuse/core";
import gsap from "gsap";

const { data: images } = await useAsyncData(
  "gallery",
  () => $fetch("/api/gallery"),
  {
    transform: (data) =>
      data
        .map((photo) => ({ photo, sort: Math.random() }))
        .sort((a, b) => a.sort - b.sort)
        .map(({ photo }) => photo),
  },
);

const scrollArea = useTemplateRef("scrollArea");
const { width } = useElementSize(() => scrollArea.value?.$el);

const lanes = computed(() => {
  if (width.value < 768) return 1;
  if (width.value < 1152) return 2;
  return 3;
});

const overlay = useOverlay();
const galleryModal = overlay.create(LazyGalleryModal);
const isModalOpen = ref(false);

const openModal = async (index: number) => {
  if (!images.value) return;
  isModalOpen.value = true;
  const instance = galleryModal.open({
    images: images.value,
    initialIndex: index,
  });

  const newIndex: number = await instance.result;
  isModalOpen.value = false;
  if (newIndex !== index && scrollArea.value?.virtualizer) {
    scrollArea.value.virtualizer.scrollToIndex(newIndex, {
      align: "center",
      behavior: "auto",
    });
  }
};

const getAspectRatio = (image: InternalApi["/api/gallery"]["get"][number]) => {
  return (image.height / image.width) * 100;
};

const isAnimating = ref(true);
const router = useRouter();

const titleText = ref("");
const descriptionText = ref("");
const backButtonText = ref("");
const showBackButtonIcon = ref(false);

const ANIMATION_SLEEP = 0.25;
const TITLE_DURATION = 1.4;
const DESCRIPTION_DURATION = 1.6;
const BACK_BUTTON_DURATION = 0.6;
const FADE_IN_DELAY = 0.3;
const FADE_IN_DURATION = 1.5;
const FADE_IN_X_FACTOR = 0.15;
const FADE_IN_Y_FACTOR = 0.075;

const title = computed(() => $t("gallery.title"));
const description = computed(() => $t("gallery.description"));
const backButton = computed(() => $t("gallery.backToHome"));

const typeText = (
  target: Ref<string>,
  text: string,
  duration: number,
  reverse = false,
  cb?: { onStart?: () => void; onComplete?: () => void },
) =>
  gsap.to(target, {
    duration,
    ease: `steps(${text.length})`,
    onUpdate() {
      const p = this.progress();
      target.value = text.slice(
        0,
        reverse ? (1 - p) * text.length : p * text.length,
      );
    },
    ...cb,
  });

const animateIntro = async () => {
  await nextTick();

  isAnimating.value = true;

  typeText(backButtonText, backButton.value, BACK_BUTTON_DURATION, false, {
    onStart: () => (showBackButtonIcon.value = true),
  }).delay(ANIMATION_SLEEP + FADE_IN_DELAY);

  typeText(titleText, title.value, TITLE_DURATION).delay(
    ANIMATION_SLEEP + FADE_IN_DELAY,
  );
  typeText(descriptionText, description.value, DESCRIPTION_DURATION).delay(
    ANIMATION_SLEEP + FADE_IN_DELAY,
  );

  gsap.fromTo(
    ".gallery-item",
    { opacity: 0 },
    {
      opacity: 1,
      duration: FADE_IN_DURATION,
      delay: ANIMATION_SLEEP,
      stagger: (i) =>
        (Math.floor(i / lanes.value) * FADE_IN_Y_FACTOR +
          (i % lanes.value) * FADE_IN_X_FACTOR) *
        FADE_IN_DURATION,
      ease: "power2.in",
    },
  );

  setTimeout(
    () => {
      isAnimating.value = false;
      scrollArea.value?.$el.focus();
    },
    (ANIMATION_SLEEP + FADE_IN_DURATION) * 1000,
  );
};

const animateOutro = async () => {
  isAnimating.value = true;

  gsap.to(".gallery-item", {
    opacity: 0,
    duration: FADE_IN_DURATION,
    delay: FADE_IN_DELAY,
    stagger: (i) =>
      (Math.floor(i / lanes.value) * FADE_IN_Y_FACTOR +
        (i % lanes.value) * FADE_IN_X_FACTOR) *
      FADE_IN_DURATION,
    ease: "power2.out",
  });

  typeText(backButtonText, backButton.value, BACK_BUTTON_DURATION, true, {
    onComplete: () => (showBackButtonIcon.value = false),
  });

  typeText(titleText, title.value, TITLE_DURATION, true);

  typeText(descriptionText, description.value, DESCRIPTION_DURATION, true, {
    onComplete: async () => {
      await promiseTimeout(ANIMATION_SLEEP * 1000);
      router.push("/");
    },
  });
};

onMounted(() => {
  animateIntro();
});
</script>

<template>
  <UScrollArea
    ref="scrollArea"
    :items="images"
    :virtualize="{
      lanes,
      gap: 24,
      estimateSize: 510,
    }"
    class="p-6 lg:p-8 xl:p-10 2xl:p-12 h-screen bg-[#0a0a0a] text-white font-[JetBrains_Mono] focus:outline-none"
    :class="{ 'no-scroll': isAnimating }"
    tabindex="0"
  >
    <template #default="{ item: image, index }">
      <header v-if="index === 0" class="pr-2 pb-6">
        <UButton
          icon="i-lucide-arrow-left"
          size="md"
          color="neutral"
          variant="link"
          :ui="{
            base: 'px-0 text-neutral-600 hover:text-neutral-400 h-8',
            leadingIcon: showBackButtonIcon
              ? 'size-4'
              : 'size-4 text-[#0a0a0a]',
          }"
          @click="animateOutro"
          >{{ backButtonText }}</UButton
        >

        <h1 class="text-3xl mt-3 font-bold relative">
          <span class="invisible">{{ title }}</span>
          <span class="absolute inset-0">{{ titleText }}</span>
        </h1>
        <p class="text-neutral-600 text-sm mt-2 w-4/5 relative">
          <span class="invisible">{{ description }}</span>
          <span class="absolute inset-0">{{ descriptionText }}</span>
        </p>
      </header>

      <div
        v-else
        class="gallery-item relative overflow-hidden rounded-sm cursor-pointer"
        :style="{ paddingBottom: `${getAspectRatio(image)}%` }"
        @click="openModal(index)"
      >
        <div class="absolute inset-0 bg-neutral-900 animate-pulse" />
        <NuxtImg
          :src="image.url"
          :width="50"
          :height="Math.round(getAspectRatio(image) / 2)"
          class="absolute inset-0 w-full h-full object-cover blur-sm scale-105"
        />
        <NuxtImg
          v-slot="{ src, isLoaded, imgAttrs }"
          :src="image.url"
          :width="600"
          :custom="true"
        >
          <img
            v-if="isLoaded"
            v-bind="imgAttrs"
            :src="src"
            loading="lazy"
            class="absolute inset-0 w-full h-full object-cover brightness-80 hover:brightness-100 transition-all"
          />
        </NuxtImg>
      </div>
    </template>
  </UScrollArea>
</template>

<style>
*::-webkit-scrollbar-track {
  border: 1px solid #000000;
  background-color: #000000;
}

*::-webkit-scrollbar {
  width: 8px;
  background-color: #000000;
}

*::-webkit-scrollbar-thumb {
  background-color: oklch(26.9% 0 0); /* neutral-800 */
  border-radius: 10px;
}

*::-webkit-scrollbar-thumb:hover {
  background-color: oklch(37.1% 0 0); /* neutral-700 */
}

@-moz-document url-prefix() {
  * {
    scrollbar-width: auto;
    scrollbar-color: oklch(37.1% 0 0) #000000;
  }
}
</style>

<style scoped>
.no-scroll {
  pointer-events: none !important;
}

.no-scroll :deep(*) {
  pointer-events: none !important;
}
</style>
