<template>
  <component v-if="isReady" :is="currentLayout" />
  <ConfirmModal />
  <VueQueryDevtools />
</template>

<script setup>
import { storeToRefs } from 'pinia'
import { computed, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useAuthStore } from '@/store/auth'
import { useModalStore } from '@/store/modal'
import AdminLayout from '@/layouts/AdminLayout.vue'
import { useGetMeQuery } from '@/services/query/auth'
import PublicLayout from '@/layouts/PublicLayout.vue'
import StudentLayout from '@/layouts/StudentLayout.vue'
import ConfirmModal from '@/components/ConfirmModal.vue'
import CounselorLayout from '@/layouts/CounselorLayout.vue'
import { tokenService } from '@/services/api/token-service'
import MissionaryLayout from '@/layouts/MissionaryLayout.vue'
import { VueQueryDevtools } from '@tanstack/vue-query-devtools'

const route = useRoute()

const layouts = {
  public: PublicLayout,
  admin: AdminLayout,
  student: StudentLayout,
  counselor: CounselorLayout,
  missionary: MissionaryLayout,
}

const currentLayout = computed(() => layouts[route.meta?.layout] || PublicLayout)

const authStore = useAuthStore()

const hasToken = computed(() => tokenService.hasToken())

const {
  data: me,
  isLoading: isMeLoading,
  isFetched: isMeFetched,
} = useGetMeQuery({ enabled: hasToken })

watch(
  me,
  (value) => {
    if (value) authStore.setUser(value)
  },
  { immediate: true }
)

const isReady = computed(() => !hasToken.value || isMeFetched.value || !isMeLoading.value)

const { modals } = storeToRefs(useModalStore())
watch(
  () => modals.value.length,
  (count) => {
    document.body.style.overflow = count > 0 ? 'hidden' : ''
  }
)
</script>
