<template>
  <div v-if="loaded.shows">
    <AddShowModal v-if="!modal" ref="addShowModal" />

    <b-button
      v-if="authStore.isSuperuser"
      variant="primary"
      data-testid="show-selector:add-show"
      class="md:tw-whitespace-nowrap"
      @click="resolvedModal.openModal()"
    >
      {{ t('showCreator.title') }}
    </b-button>
  </div>
</template>

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

import AddShowModal from './AddShowModal.vue'
import { useI18n } from '@/i18n'
import { useAuthStore } from '@/stores/auth'

type Modal = {
  openModal: () => void
}

const props = defineProps<{
  modal?: Modal
}>()

const store = useStore()
const authStore = useAuthStore()
const { t } = useI18n()

const addShowModal = ref<Modal>()
const resolvedModal = computed(() => (props.modal ?? addShowModal) as unknown as Modal)
const loaded = computed(() => ({
  shows: store.state.shows.loaded.shows,
  types: store.state.shows.loaded.types,
  fundingCategories: store.state.shows.loaded.fundingcategories,
}))

// TODO: not sure these belong here.
if (!loaded.value.types) {
  store.dispatch('shows/fetchMetaArray', { property: 'types', onlyActive: true })
}

if (!loaded.value.fundingCategories) {
  store.dispatch('shows/fetchMetaArray', { property: 'fundingcategories', onlyActive: true })
}
</script>