<script setup lang="ts">
import { onMounted, ref } from 'vue'

import type { GalleryEntry, GalleryList } from 'src/types/galleries/galleryList'
import { type GalleryListDefinition } from 'content/routes.js'
import { amendVariantsWithDefaults, getTitleFromEntryOrId } from 'src/utilities/galleries'
import { fetchAndParseYaml } from 'src/utilities/fetch'
import { getCurrentRoute } from 'src/utilities/vuetils'
import { useRouteStore } from 'src/routes'

const props = defineProps<{
  variants: string[]
}>()

const ready = ref(false)
const config = ref(null! as GalleryList)
const entry = ref(null! as GalleryEntry)
const id = ref('')
const currentRoute = getCurrentRoute()
const routeStore = useRouteStore()
const routeConfig = routeStore._routes[currentRoute.path.substring(0, currentRoute.path.length - 5)] as GalleryListDefinition
const routeSubConfig = routeStore._routes[currentRoute.path]
const title = ref('')

onMounted(async () => {
  config.value = await fetchAndParseYaml<GalleryList>(routeConfig.config)
  let currentEntries = config.value.entries
  for (let i = 0; i < props.variants.length - 1; ++i) {
    currentEntries = amendVariantsWithDefaults(currentEntries[props.variants[i]])!
  }
  entry.value = currentEntries[props.variants[props.variants.length - 1]]
  id.value = props.variants[props.variants.length - 1]
  title.value = getTitleFromEntryOrId(entry.value, id.value)
  document.title = routeSubConfig.title.replace('$ENTRY', title.value)
  ready.value = true
})
</script>

<template lang="pug">
.template.gallery-view
  .view-wrapper(
    v-if='ready'
  )
    .view-outlet
      img(
        :src='entry.url || entry.thumbnailUrl'
      )
    p {{ title }}
</template>

<style scoped lang="sass">

</style>
