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

const images = ref<InternalApi["/api/gallery"]["get"]>([]);

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

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

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

const lanes = ref(3);

const updateLanes = () => {
  if (window.innerWidth < 768) {
    lanes.value = 1;
  } else if (window.innerWidth < 1152) {
    lanes.value = 2;
  } else {
    lanes.value = 3;
  }
};

const { data: galleryPhotos } = await useAsyncData("gallery", () =>
  $fetch("/api/gallery"),
);

onMounted(() => {
  if (!galleryPhotos.value) return;

  // shuffle
  images.value = galleryPhotos.value
    .map((photo) => ({ photo, sort: Math.random() }))
    .sort((a, b) => a.sort - b.sort)
    .map(({ photo }) => photo);

  updateLanes();
  window.addEventListener("resize", updateLanes);
});

onUnmounted(() => {
  window.removeEventListener("resize", updateLanes);
});
</script>

<template>
  <UScrollArea
    ref="scrollArea"
    :items="images"
    :virtualize="{
      lanes,
      gap: 24,
      estimateSize: (index) => {
        if (index === 0) return 150;
        return 330;
      },
    }"
    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 macro photography of insects and
          flowers.
        </p>
      </header>

      <div
        v-else
        class="relative overflow-hidden rounded-sm cursor-pointer"
        @click="openModal(index)"
      >
        <img
          :src="image.url"
          loading="lazy"
          class="w-full h-auto block brightness-80 hover:brightness-100 transition-all"
        />
      </div>
    </template>
  </UScrollArea>
</template>
