<template>
  <div
    class="tw-grid tw-gap-6 tw-grid-cols-[repeat(auto-fill,minmax(var(--grid-item-width),1fr))] [--grid-item-width:300px] lg:[--grid-item-width:350px] tw-mx-auto"
  >
    <template v-for="(show, index) in showList" :key="show.id">
      <template v-if="index === splitIndex && splitIndex !== 0">
        <div class="tw-col-span-full">
          <hr class="tw-w-full" />
          <h2 class="tw-text-3xl tw-font-black tw-m-0 tw-mt-8">
            {{ t('showListGrid.otherShows') }}
          </h2>
        </div>
      </template>
      <ShowListGridItem
        :show="show"
        :data-show-grid-item="index"
        @focus="lastFocusedShowIndex = index"
      />
    </template>

    <div class="tw-col-span-full tw-flex tw-justify-center">
      <button v-if="hasMore" class="btn btn-default" @click="loadMore">
        {{ t('loadMoreItems', { items: t('show.plural') }) }}
      </button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { PaginatedListResult } from '@rokoli/bnb/drf'
import { computed, ref } from 'vue'
import { Show } from '@/types'
import { useI18n } from '@/i18n'
import { useAuthStore } from '@/stores/auth'
import ShowListGridItem from './ShowListGridItem.vue'

defineOptions({ compatConfig: { MODE: 3 } })

const props = defineProps<{
  shows: PaginatedListResult<Show>[]
  split: boolean
  hasMore?: boolean
}>()
const emit = defineEmits<{ loadMore: [] }>()
const { t } = useI18n()
const { steeringUser } = useAuthStore()
const lastFocusedShowIndex = ref(0)
const showList = computed(() => props.shows.flatMap((shows) => shows.items))
const splitIndex = computed(() => {
  if (!props.split) return -1
  const id = steeringUser?.id
  return id ? showList.value.findIndex((show) => !show.ownerIds.includes(id)) : -1
})

function loadMore() {
  emit('loadMore')
  const el = document.querySelector<HTMLAnchorElement>(
    `[data-show-grid-item="${lastFocusedShowIndex.value}"]`,
  )
  if (el) el.focus()
}
</script>