<script setup>
import { onMounted, ref } from 'vue'

import AppBar from '@/components/AppBar.vue'
import ContentLoading from '@/components/ContentLoading.vue'
import ModalContainer from '@/components/ModalContainer.vue'
import PageContainer from '@/components/PageContainer.vue'
import PageContent from '@/components/PageContent.vue'
import TermsRequest from '@/components/TermsRequest.vue'
import { useApartmentStore } from '@/stores/apartments'
import { useBuildingStore } from '@/stores/buildings'
import { useSessionStore } from '@/stores/session'

const isLoading = ref(true)
const showModal = ref(false)

const apartments = useApartmentStore()
const buildings = useBuildingStore()
const session = useSessionStore()

function handleModal() {
  showModal.value = false
}

onMounted(() => {
  Promise.all([
    session.fetchSelf(),
    apartments.fetchApartments()
  ])
    .then(async () => {
      let buildingId, apartmentId

      if (apartments.data.length > 0) {
        buildingId = apartments.data[0].linkedTo
        apartmentId = apartments.data[0]._id

        apartments.setActiveApartment(apartmentId)
      }

      await buildings.fetchBuildingById(buildingId)
    })
    .finally(() => {
      isLoading.value = false
    })
})
</script>

<template>
  <PageContainer v-if="!isLoading">
    <AppBar />
    <PageContent>
      <router-view></router-view>
    </PageContent>
  </PageContainer>
  <ContentLoading v-else />
  <ModalContainer v-if="!session.self?.sharingAllowed" :permanent="true">
    <TermsRequest @on-close-modal="handleModal" />
  </ModalContainer>
</template>