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

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;
};
</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]"
  >
    <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',
            leadingIcon: 'size-4',
          }"
          >Back to Home</UButton
        >

        <h1 class="text-3xl mt-3 font-bold">Pihkaal's Gallery</h1>
        <p class="text-neutral-600 text-sm mt-2 w-4/5">
          Started on March 2025. I love taking photos of plants, insects, and
          arachnids.
        </p>
      </header>

      <div
        v-else
        class="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"
          :fetchpriority="isModalOpen ? 'low' : 'auto'"
        >
          <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>
